Let's play the minesweeper game (Wikipedia,online game)!
You are given a 2D char matrix representing the game board.'M'represents anunrevealedmine,'E'represents anunrevealedempty square,'B'represents arevealedblank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines,digit('1' to '8') represents how many mines are adjacent to thisrevealedsquare, and finally'X'represents arevealedmine.
Now given the next click position (row and column indices) among all theunrevealedsquares ('M' or 'E'), return the board after revealing this position according to the following rules:
class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int x = click[0], y = click[1];
if (board[x][y] == 'M'){
board[x][y] = 'X';
}
else{
int count = 0;
for (int i = -1; i < 2; i++){
for (int j = -1; j < 2; j++){
if (i == 0 && j == 0) continue;
int xx = x + i;
int yy = y + j;
if (xx < 0 || xx >= board.length || yy < 0 || yy >= board[0].length) continue;
if (board[xx][yy] == 'M') count++;
}
}
if (count > 0){
board[x][y] = (char)('0' + count);
}
else{
board[x][y] = 'B';
for (int i = -1; i < 2; i++){
for (int j = -1; j < 2; j++){
if (i == 0 && j == 0) continue;
int xx = x + i;
int yy = y + j;
if (xx < 0 || xx >= board.length || yy < 0 || yy >= board[0].length) continue;
if (board[xx][yy] == 'E') updateBoard(board, new int[]{xx, yy});
}
}
}
}
return board;
}
}