很直接的做法,按照题目的要求实现就可以。代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) { | |
int m = board.size(), n = m? board[0].size(): 0, row = click[0], col = click[1]; | |
if(board[row][col] == 'M') | |
board[row][col] = 'X'; | |
else | |
{ | |
int mines = adj(board, row, col); | |
if(mines) | |
board[row][col] = '0' + mines; | |
else | |
{ | |
board[row][col] = 'B'; | |
vector<int> dirs = {-1, 0, 1}; | |
for(auto dx : dirs) | |
{ | |
for(auto dy : dirs) | |
{ | |
if(!dy && !dx)continue; | |
int x = row + dx, y = col + dy; | |
if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') | |
{ | |
vector<int> nextClick = {x, y}; | |
updateBoard(board, nextClick); | |
} | |
} | |
} | |
} | |
} | |
return board; | |
} | |
private: | |
int adj(vector<vector<char>>& board, int row, int col) | |
{ | |
int m = board.size(), n = m? board[0].size(): 0; | |
vector<int> dirs = {-1, 0, 1}; | |
int count = 0; | |
for(auto dx : dirs) | |
{ | |
for(auto dy : dirs) | |
{ | |
if(!dy && !dx)continue; | |
int x = row + dx, y = col + dy; | |
if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M')++count; | |
} | |
} | |
return count; | |
} | |
}; |
No comments:
Post a Comment