题目链接:https://leetcode-cn.com/problems/minesweeper/
解题思路:
(1)首先判断初始坐标点是否为地雷,如果是则设置该位置为X,并返回board;
(2)如果初始坐标点不为地雷,则从初始坐标点进行dfs,但是需注意我们要将地雷旁边的未别挖过的空白方块设置为相邻地雷的数量,此在进行dfs时首先要判断该空白方块周围是否有地雷,可用变量count来记录周围地雷的数量,如果count 不为0,则设置board[x][y] = count + '0',否则则设置board[x][y] = 'B', 并进行dfs。
class Solution {
void dfs(char[][] board, int m, int n, int x, int y){
int count = 0;
for (int i = -1; i <= 1; i++){
for (int j = -1; j <= 1; j++){
int nx = x + i;
int ny = y + j;
if (nx >= 0 && nx < m && ny >= 0 && ny < n){
//判断该空白方块周围是否有地雷
if (board[nx][ny] == 'M') count++;
}
}
}
if (count != 0){
board[x][y] =(char) (count + '0');
}
else{
board[x][y] = 'B';
for (int i = -1; i <= 1; i++){
for (int j = -1; j <= 1; j++){
int nx = x + i;
int ny = y + j;
if (nx >= 0 && nx < m && ny >= 0 && ny < n && board[nx][ny] == 'E'){
dfs(board, m, n, nx, ny);
}
}
}
}
}
public char[][] updateBoard(char[][] board, int[] click) {
int x = click[0];
int y = click[1];
int m = board.length;
int n = board[0].length;
if (board[x][y] == 'M'){
board[x][y] = 'X';
} else {
dfs(board, m, n, x, y);
}
return board;
}
}