扫雷递归,stackoverflow

时间:2017-04-28 04:34:26

标签: java recursion minesweeper

所以,我一直在研究一些针对扫雷的java代码。我正在努力尝试获取空的单元格,以递归方式显示它们旁边的重合单元格。这是执行此操作的功能。

“单元格”是我用于游戏中的单元格的按钮。

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'绑定的末尾时,它返回,但随后立即跳转到下一个递归调用,将其带到相同的'x'位置。

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

我想知道我需要什么样的限定符以及我需要放置它以确保它不会在同一地点搜索两次。提前谢谢!

1 个答案:

答案 0 :(得分:1)

您正在创建一个无限循环,因为每个单元格将重复到每个相邻的单元格,然后每个单独的单元格将重新返回到原始单元格等。

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

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

由于名为短路的便捷功能,如果isDisabled()xy,则setDisabled(true)的检查甚至会引发错误超出范围,因为它永远不会被评估。

编辑:回答您关于将findMines()放在哪里的后续行动 - 您总是希望在单击该单元后禁用该单元格,对吗?因此,在if声明之前将其放在 function runEveryWeek(){ sleep(/*for 2 weeks*/); runEveryWeek(); } 下。

相关问题