我的 friend 正在制作一个扫雷克隆,他要求我帮助完成以下部分:当您单击非地雷/非数字“空白”方 block 时,它会显示所有相邻的空白。以下是我写的代码。我不明白为什么它永远不会解决。
我的基本情况应该是当 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);
}
}
}
}
最佳答案
让我们考虑一下 r==0
和 c==0
的情况,并假设 buttons[0][0].value == 0
和 buttons[0][0].isCovered == false
。
循环的第一次迭代将导致函数使用相同的参数 0, 0
调用自身,并且 value
和 的状态保持不变已覆盖
。这将立即导致无限递归。
附注查看Wikipedia article对于其他洪水填充算法。
关于java - 无法弄清楚为什么递归永远无法解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9368123/