0

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

我的基本情况应该是当 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);
            }
        }
    }

}
4

3 回答 3

2

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

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

PS 查看Wikipedia 文章了解其他洪水填充算法。

于 2012-02-20T20:47:38.087 回答
0

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

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

? 或者您的支票应该是:

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

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

于 2012-02-20T20:49:23.680 回答
0

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

于 2012-02-20T20:56:08.243 回答