【问题标题】:Can't figure out why recursion never resolves无法弄清楚为什么递归永远不会解决
【发布时间】:2012-02-20 20:43:43
【问题描述】:

我的朋友正在制作一个扫雷克隆,他让我帮忙解决当您单击非地雷/非数字“空白”方块时,它会显示所有相邻空白的部分。以下是我写的代码。我不知道为什么它永远不会解决。

我的基本情况应该是当 for 循环完全执行并且 if 语句永远不会返回 true 时。

我有什么遗漏吗?

顺便说一句,这是在java中。另外,我告诉他应该将整个按钮状态更改分配给一个方法:p

public void revealAdjacentNulls(int r, int c)
{
    int ir, ic;

    //literal edge cases :P

    int rmax = (r == 15) ? r : r + 1;
    int cmax = (c == 15) ? c : c + 1;

    //check all spaces around button at r,c

    for(ir = (r==0) ? 0 : r-1; ir <= rmax; ir++){

        for (ic = (c==0) ? 0 : c-1; ic <= cmax; ic++){

            //if any are blank and uncovered, reveal them, then check again around the blanks

            if (buttons[ir][ic].value == 0 && buttons[ir][ic].isCovered == false)
            {
                buttons[ir][ic].setEnabled(false);  //number uncovered
                buttons[ir][ic].setBackground(Color.blue);
                buttons[ir][ic].setText(Character.toString(buttons[ir][ic].value));
                buttons[ir][ic].isCovered = false;
                revealAdjacentNulls(ir, ic);
            }
        }
    }

}

【问题讨论】:

  • for(ir = (r==0) ? 0 : r-1; ir &lt;= rmax; ir++){。没有。只是没有。

标签: java recursion minesweeper


【解决方案1】:

让我们考虑r==0c==0 的情况,假设buttons[0][0].value == 0buttons[0][0].isCovered == false

循环的第一次迭代将导致函数使用相同的参数0, 0 调用自身,并且valueisCovered 的状态保持不变。这将立即导致无限递归。

附:查看Wikipedia article 了解其他洪水填充算法。

【讨论】:

  • 在调用函数之前,isCovered(第一个值)的状态设置为false。另外,我会检查一下。
  • @user1221803:我强烈怀疑您的isCovered 处理是错误的。您的意思是在循环内设置为true 而不是false
【解决方案2】:

一方面,它会一直递归revealAdjacentNulls(r, c)。您的条件是 isCovered 必须为 false - 但您也将 设置 isCovered 为 false。你的意思是写:

buttons[ir][ic].isCovered = true;

?或者您的支票应该是:

if (buttons[ir][ic].value == 0 && buttons[ir][ic].isCovered)

(这取决于您所说的“被覆盖”。)

【讨论】:

    【解决方案3】:

    另一种情况:如果 r == 15,则循环将从 14 (r - 1) 到 15 (rmax)。如果您的 if 语句为真,那么将有无限递归。这同样适用于 c。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      相关资源
      最近更新 更多