题目
Let's play the minesweeper game (Wikipedia, online game)!
You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank 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 this revealed square, and finally 'X' represents a revealed mine.
Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules:
- If a mine ('M') is revealed, then the game is over - change it to 'X'.
- If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively.
- If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
- Return the board when no more squares will be revealed.
答案
题目特别绕,但是思路很简单。。其实就是照题目说的做,没有什么思路可言。。
class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
// If click is outside board, return
if(click[0] < 0 || click[0] >= board.length || click[1] < 0 || click[1] >= board[0].length)
return board;
int cnt = 0;
char c = board[click[0]][click[1]];
if(c == 'M') {
// Change to X, Then Game Over
board[click[0]][click[1]] = 'X';
}
else if(c == 'E') {
// Change to B/Digit depending on neighbors
for(int i = -1; i <= 1; i++) {
for(int j = -1; j <= 1; j++) {
if(i == 0 && j == 0) continue;
int x = click[0] + i, y = click[1] + j;
if(x < 0 || x >= board.length || y < 0 || y >= board[0].length) continue;
if(board[x][y] == 'M' || board[x][y] == 'X') cnt++;
}
}
if(cnt == 0)
board[click[0]][click[1]] = 'B';
else {
board[click[0]][click[1]] = Integer.toString(cnt).charAt(0);
return board;
}
// Recursively reveal neighboring tiles
for(int i = -1; i <= 1; i++) {
for(int j = -1; j <= 1; j++) {
if(i == 0 && j == 0) continue;
int x = click[0] + i, y = click[1] + j;
updateBoard(board, new int[]{x, y});
}
}
}
return board;
}
}