首页 > 解决方案 > 递归函数似乎不起作用

问题描述

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

所以我认为递归函数最适合这个问题,对吧?我的(伪)代码是这样的:

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

然而,只有最后一张牌会被移动!老实说,我在编写递归函数方面并不是最好的。知道我的问题是什么吗?

标签: 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);
        if (position at row, column is empty)
            move card to the right;
    }

请注意,您必须再次检查该位置是否为空,以防递归调用无法移动卡片,因为右侧的所有空间都已满。

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


推荐阅读