繁体   English   中英

游戏扫雷器中二维数组递归的 StackOverflowError

[英]StackOverflowError on recursion in 2-D array in game Minesweeper

有一个函数可以通过规则探索 x 和 y 周围的单元格:

如果单元格是空的并且周围没有地雷,则可以探索其周围的所有单元格,包括标记的单元格

我使用递归来解决它,但捕获 StackOverflowError。 由 isEmptyAndNoMinesAround(int x, int y) 实现的基本情况。 地雷标记为“X”。

 public void exploreCell(int x, int y, String type) {

    if (!isEmptyAndNoMinesAround(x, y)) { //If the cell is empty and has no mines around, all the cells around it, including the marked ones, can be explored
        return;
    }

    userfield[x][y].setType(minefield[x][y].getType()); //explore cell on field

    //recur neighbors explore
    for (int xoff = -1; xoff <= 1; xoff++) {
        for (int yoff = -1; yoff <= 1; yoff++) {
            
            int i = x + xoff;
            int j = y + yoff;
            if (i > -1 && x < FIELD_SIZE && j > -1 && y < FIELD_SIZE) { //bound check

                exploreCell(i, j, type);

            }
        }
    }
}


    private boolean isEmptyAndNoMinesAround(int x, int y) {
    return minefield[x][y].getType() != 'X' && countMinesAround(x, y) == 0;
}

如果您有两个相邻的单元格满足条件,您只需在两者之间无休止地跳跃。 您必须确保不会重新访问相同的方块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM