我正在尝试制作MineSweeper的控制台版本。
尽管我目前努力,但我无法弄清楚MineSweeper的“洪水填充”部分,如果选择的广场附近没有炸弹,我们现在必须检查那些相邻的方块以找到相邻的炸弹。
以下代码适用于所选方块与炸弹相邻的情况:
// checking the adjacent cells, I made -1 = to the bomb value, rest of the cells
// are default(0)
public void sweep(int r, int c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)
return;
int minRow = 0, minCol = 0, maxRow = 0, maxCol = 0, neighborBomb = 0;
// means if I clicked a bomb, end the program
if (grid[r][c] == -1) {
System.out.println("Your selection [" + r + ", " + c + "] contained a bomb. .\nGAME OVER");
System.exit(0);
}
// Series of if/else to find the min & max row col size to avoid going out of
// bounds
if (r == 0)
minRow = 0;
else
minRow = r - 1;
if (r == grid.length - 1)
maxRow = r;
else
maxRow = r + 1;
if (c == 0)
minCol = 0;
else
minCol = c - 1;
if (c == grid[0].length - 1)
maxCol = c;
else
maxCol = c + 1;
//if the selected cell is 0 & has not been searched yet.
if (grid[r][c] == 0 && recurseSearch[r][c] == false) {
recurseSearch[r][c] = true;
// search adjacent cells to see how many bombs surround the cell in question
neighborBomb = 0;
for (int row = minRow; row <= maxRow; row++) {
for (int col = minCol; col <= maxCol; col++) {
if (grid[row][col] == -1) {
neighborBomb++;
}
}
}
}
// cell will now display how many bombs are adjacent
if (neighborBomb > 0) {
grid[r][c] = neighborBomb;
return;
}
//HERE I WANT TO CHECK ALL ADJACENT SQUARES BUT IT WILL ONLY RUN
//sweep(r+1, c) rather than all the surrounding squares
else {
sweep(r + 1, c);
sweep(r - 1, c);
sweep(r + 1, c + 1);
sweep(r + 1, c - 1);
sweep(r - 1, c + 1);
sweep(r - 1, c - 1);
sweep(r, c + 1);
sweep(r, c - 1);
}
}
grid [] []本质上是我的游戏板,recurseSearch [] []是一个布尔值,可以跟踪是否已经搜索过一个单元格。 if / else语句的混乱是我试图得不到任何IndexOutOfBoundErrors。 当我试图奔跑并挑选一个没有被炸弹包围的牢房时,我得到了
Exception in thread "main" java.lang.StackOverflowError
并重复
的行 sweep(r + 1, c);
sweep(r - 1, c);
任何想法/建议对于如何让我的递归实际检查原始r,c的每个相邻单元格都有帮助!
答案 0 :(得分:2)
在支票
之后递归调用您的方法//if the selected cell is 0 & has not been searched yet.
if (grid[r][c] == 0 && recurseSearch[r][c] == false) {
recurseSearch[r][c] = true;
// ...
}
因此,您重复已访问过的字段的递归
但递归应该只发生在 这个if块中。
答案 1 :(得分:0)
如果已经使用IBAction
处理了一个单元格,你想跟踪它是不错的,但是你没有正确地中断递归。
将第一个表达式更改为:
recurseSearch[][]