gpt4 book ai didi

Java 扫雷 StackOverFlowError 递归

转载 作者:行者123 更新时间:2023-12-02 02:23:56 25 4
gpt4 key购买 nike

我正在尝试制作一个控制台版本的扫雷。

尽管我目前很努力,但我无法弄清楚扫雷的“洪水填充”部分,如果所选方格的周围邻居不包含炸弹,我们现在必须检查这些相邻方格以找到相邻方格炸弹。

下面的代码适用于所选方 block 与炸弹相邻的情况:

// 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[][] 是一个 boolean 值,它将跟踪单元格是否已被搜索。if/else 语句的困惑是我试图不得到任何 IndexOutOfBoundErrors。当我尝试运行并选择一个没有被炸弹包围的单元格时,我得到

   Exception in thread "main" java.lang.StackOverflowError

它会重复以下行

   sweep(r + 1, c);
sweep(r - 1, c);

任何想法/建议都会有助于如何使我的递归实际检查所选原始 r,c 的每个相邻单元格!

最佳答案

您在检查后递归调用您的方法

//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 block 内。

关于Java 扫雷 StackOverFlowError 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48068529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com