recursion - 递归函数似乎不起作用
问题描述
所以我正在编写这个应用程序,用户可以在其中将对象(卡片)放在墙上。如果墙上的位置已经被一张牌占据,则需要移动这张牌。但是,如果下一个位置也已经被占用,我们也必须移动该卡,依此类推。
所以我认为递归函数最适合这个问题,对吧?我的(伪)代码是这样的:
private void moveCard(int row, int column){ //row, column = position on the wall
if(column >= length of wall)
return;
if(position at row, column is empty)
move card to the right;
else
moveCard(row, column+1);
然而,只有最后一张牌会被移动!老实说,我在编写递归函数方面并不是最好的。知道我的问题是什么吗?
解决方案
将右侧的卡片移开后,您必须移动当前卡片。
private void moveCard(int row, int column){ //row, column = position on the wall
if(column >= length of wall)
return;
if(position at row, column is empty)
move card to the right;
else {
moveCard(row, column+1);
if (position at row, column is empty)
move card to the right;
}
请注意,您必须再次检查该位置是否为空,以防递归调用无法移动卡片,因为右侧的所有空间都已满。
您还可以让函数返回一个布尔值,指示它是否成功移动卡片,您可以检查它而不是测试空间是否为空。
推荐阅读
- axios - Axios-重定向问题
- python - ODEINT 错误 - ValueError: setting an array element with a sequence (Python model of solar system)
- javascript - 需要有人解释一个关于循环的简单问题
- css - 移动视图中的 CSS 图像保持率
- c++ - 以最小化状态启动 chromium 浏览器 (Win32/WinAPI)
- jenkins - 获取 Jenkins 工作区文件
- r - 使用 facet_wrap 在每个构面中放置 2 行或更多行
- python - Python / Matplotlib / 绘制函数
- python - Python flask - SQLAlchemy 查询结果未按预期传递给 jinja 模板
- google-cloud-dns - Cloud DNS 加载失败