1、如果一个地雷(‘M’)被挖出,游戏就结束了- 把它改为 ‘X’。
2、如果一个没有相邻地雷的空方块(‘E’)被挖出,修改它为(‘B’),并且所有和其相邻的未挖出方块都应该被递归地揭露。
3、如果一个至少与一个地雷相邻的空方块(‘E’)被挖出,修改它为数字(‘1’到’8’),表示相邻地雷的数量。
4、如果在此次点击中,若无更多方块可被揭露,则返回面板。
[[‘E’, ‘E’, ‘E’, ‘E’, ‘E’],
[‘E’, ‘E’, ‘M’, ‘E’, ‘E’],
[‘E’, ‘E’, ‘E’, ‘E’, ‘E’],
[‘E’, ‘E’, ‘E’, ‘E’, ‘E’]]
Click : [3,0]
[[‘B’, ‘1’, ‘E’, ‘1’, ‘B’],
[‘B’, ‘1’, ‘M’, ‘1’, ‘B’],
[‘B’, ‘1’, ‘1’, ‘1’, ‘B’],
[‘B’, ‘B’, ‘B’, ‘B’, ‘B’]]
给出BFS代码:
public void bfs(char[][] board, int x, int y) {
Queue<int[]> q = new LinkedList<>();
q.offer(new int[] { x, y });
boolean v[][] = new boolean[board.length][board[0].length];
v[x][y] = true;
while (!q.isEmpty()) {
int cnt = 0;
int pos[] = q.poll();
// 先判断周围八个方向的格子
for (int k = 0; k < 8; k++) {
int newX = pos[0] + dx[k];
int newY = pos[1] + dy[k];
if (newX < 0 || newY < 0 || newX >= board.length || newY >= board[0].length) {
continue;
}
if (board[newX][newY] == 'M') {
cnt++;
}
}
if (cnt > 0) {// 周围有雷,直接修改
board[pos[0]][pos[1]] = (char) (cnt + '0');
} else {
// 说明周围没雷
board[pos[0]][pos[1]] = 'B';
for (int k = 0; k < 8; k++) {
int newX = pos[0] + dx[k];
int newY = pos[1] + dy[k];
// 不是E不需要访问,或者已经在访问队列q中了
if (newX < 0 || newY < 0 || newX >= board.length || newY >= board[0].length
|| board[newX][newY] != 'E' || v[newX][newY]) {
continue;
}
q.offer(new int[] { newX, newY });
v[newX][newY] = true;
}
}
}
}
给出DFS代码:
int cnt = 0;
for (int i = 0; i < 8; i++) {
int tx = x + dx[i];
int ty = y + dy[i];
if (tx < 0 || ty < 0 || tx > board.length || ty > board[0].length) {
continue;
}
if (board[tx][ty] == 'M') {
cnt++;
}
}
if (cnt > 0) {
board[x][y] = (char) (cnt + '0');
return;
} else {
board[x][y] = 'B';
for (int i = 0; i < 8; i++) {
int tx = x + dx[i];
int ty = y + dy[i];
if (tx < 0 || ty < 0 || tx > board.length || ty > board[0].length || board[tx][ty] != 'E') {
continue;
}
dfs(board, tx, ty);
}
}