扫雷递归,stackoverflow

Minesweeper recursion, stackoverflow

所以,我一直在为 java 编写扫雷程序的一些代码。我正在努力尝试让空单元格递归地显示它们旁边的重合单元格。这是执行此操作的函数。

"cell" 是我在游戏中用于单元格的按钮。

private void showCells(int x, int y) {

    //checks out of bounds
    if (x >= SIZE || y >= SIZE || x <= 0 || y <= 0) {
        return;
    }

    //function to look at each surrounding cell and see if it is a mine, 
    //has nMines as a global variable to keep track of the number of mines
    findMines(x, y);

    //if there are mines around the cell that was selected
    if (nMines > 0) {

        //set the text of that cell to the number of mines around it
        cell[x][y].setText(String.valueOf(nMines));

        //if cell is not already disabled, disable it
        if (!cell[x][y].isDisabled()) {
            cell[x][y].setDisable(true);
        }
    } else {

        //if there are no mines, recursively show the surrounding mines
        showCells(x + 1, y);
        showCells(x - 1, y);
        showCells(x, y + 1);
        showCells(x, y - 1);
    }

    //resets the mine count for the next search
    nMines = 0;
}

我知道就功能而言,我的代码还有一些其他问题,但我正在尝试弄清楚这个递归问题。当我调试时发生的事情是,当我到达 'x' 边界的末尾时,它 returns,但随后立即跳转到下一个递归调用,它将它带到相同的 [=21] =] 位置。

showCells(x + 1, y);
showCells(x - 1, y);

我想知道我需要什么样的限定词以及我需要把它放在哪里以确保它不会在同一个地方搜索两次。提前致谢!

您正在创建一个无限循环,因为每个单元格都会递归到每个相邻单元格,然后每个空单元格都会递归到原始单元格,依此类推。

您可以通过在第一个 if 语句中添加条件来解决此问题:

if (x >= SIZE || y >= SIZE || x <= 0 || y <= 0 || cell[x][y].isDisabled()) {
    return;
}

由于一个方便的功能叫做短路isDisabled()的检查甚至不会在x或[=13时抛出错误=] 超出范围,因为它永远不会被评估。

编辑:回答您关于放置 setDisabled(true) 的后续问题 - 您总是希望在单击单元格后禁用它,对吗?所以把它放在 findMines() 的正下方,在 if 语句之前。