递归函数似乎不起作用

时间:2018-08-29 19:24:33

标签: recursion

因此,我正在编写此应用程序,用户可以在其中将物体(卡片)放在墙上。如果墙上的位置已被卡片占用,则需要移动该卡片。但是,如果还下一个位置,我们也必须移动该卡,依此类推。

因此,我认为递归函数将是解决此问题的最佳方法,对吗? 我的(伪)代码是这样的:

{{1}}

但是,只有连续的最后一张卡被移动!老实说,我并不是编写递归函数的最佳人选。知道我的问题是什么吗?

1 个答案:

答案 0 :(得分:0)

在右侧移动卡后,必须移动当前卡。

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;
    }

请注意,如果由于右侧的所有空格已满而导致递归调用无法移动卡,则必须再次检查该位置是否为空。

您还可以让该函数返回一个布尔值,该布尔值指示是否成功移动了卡,并且可以检查而不是测试空间是否为空。

相关问题