0
我一直在尝试做一个扫雷游戏,给出单元格的坐标,它会递归地揭示相邻的单元格,直到找到与炸弹相邻的单元格。我有一个方法,给定坐标x和y计算它周围有多少个地雷。在扫雷板上递归映射地雷
// Counts how many mines are adjacent to a given coordinate cell if any
void board::mineCount(int x, int y) {
// North
if (y > 0) {
if (board[x][y - 1].hasMine) {
board[x][y].mineCount++;
}
}
// South
if (y < dimensions[1] - 1) {
if (board[x][y + 1].hasMine) {
board[x][y].mineCount++;
}
}
// East
if (x < dimensions[0] - 1) {
if (board[x + 1][y].hasMine) {
board[x][y].mineCount++;
}
}
// West
if (x > 0) {
if (board[x - 1][y].hasMine) {
board[x][y].mineCount++;
}
}
// North East
if (x < dimensions[0] - 1 && y > 0) {
if (board[x + 1][y - 1].hasMine) {
board[x][y].mineCount++;
}
}
// North West
if (x > 0 && y > 0) {
if (board[x - 1][y - 1].hasMine) {
board[x][y].mineCount++;
}
}
// South East
if (x < dimensions[0] - 1 && y < dimensions[1] - 1) {
if (board[x + 1][y + 1].hasMine) {
board[x][y].mineCount++;
}
}
// South West
if (x > 0 && y < dimensions[1] - 1) {
if (board[x - 1][y + 1].hasMine) {
board[x][y].mineCount++;
}
}
}
每个小区是具有mineCount
字段得到由1地雷被发现邻近它每次递增一个结构。我无法弄清楚我的递归逻辑会去哪里。我试着做类似:
// North
if (y > 0) {
if (board[x][y - 1].hasMine) {
board[x][y].mineCount++;
} else {
minecount(x, y-1);
}
}
对于每个位置,但无济于事。任何指针将不胜感激。
你试过的递归行为是什么?它有什么问题? – Tyler
不相关:节省自己很多努力,并在开始时计算每个网格坐标的矿场数。它应该让你大幅削减这个逻辑,并使你更容易发现你的bug /解决方案。 – user4581301