Description:
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.
**Example2: **
Input: [['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'M', 'E', 'E'], ['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E']] Click : [3,0] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']]
Explanation:

**Example1: **
Input: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] Click : [1,2] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'X', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']]Explanation:

Link:
https://leetcode.com/problems/minesweeper/#/description
解題方法:
一道挺無聊的題,具體步驟題目說明已經(jīng)給出,使用尾遞歸解決,并且LeetCode的程序也有點問題(比如在掃雷中數(shù)字是不能走的)。
能點的方塊有:'M', 'E'
不能點的方塊有:'B', '1~8', 'X'
點到M游戲結(jié)束,點到E如果周邊沒有地雷則繼續(xù)遞歸,如果有雷則顯示雷的數(shù)量。
Tips:
整個遞歸過程中使用一個 bool變量gameover控制游戲能否進行。
完整代碼:
vector<int> dirX = {-1, -1, -1, 0, 0, 1, 1, 1};
vector<int> dirY = {-1, 0, 1, -1, 1, -1, 0, 1};
class Solution
{
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click)
{
bool gameover = false; //控制游戲能否繼續(xù)
go(click[0], click[1], board, gameover);
return board;
}
void go(int x, int y, vector<vector<char>>& board, bool gameover)
{
if(!isValid(x, y, board) || gameover || (board[x][y] >= 48 && board[x][y] <= 56) || board[x][y] == 'X' || board[x][y] == 'B')
return;
if(board[x][y] == 'M')
{
gameover = true;
board[x][y] = 'X';
return;
}
int cnt = countMine(x, y, board);
if(cnt != 0)
{
board[x][y] = cnt + 48;
return;
}
board[x][y] = 'B';
for(int i = 0; i < 8; i++)
go(x+dirX[i], y+dirY[i], board, gameover);
}
bool isValid(int x, int y, vector<vector<char>>& board)
{
if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size())
return false;
return true;
}
int countMine(int x, int y, vector<vector<char>>& board)
{
int cnt = 0;
for(int i = 0; i < 8; i++)
{
if(isValid(x + dirX[i], y + dirY[i], board) && board[x+dirX[i]][y + dirY[i]] == 'M')
cnt++;
}
return cnt;
}
};