乍一看有点复杂,其实就完全按照每个规则实现就行。
class Solution {
private:
int dx[8]={0,0,1,-1,1,1,-1,-1};
int dy[8]={1,-1,0,0,1,-1,1,-1};
int n,m;
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int x=click[0],y=click[1];
n=board.size(),m=board[0].size();
if(board[x][y]=='M'){
board[x][y]='X';
}else{
dfs(board,x,y);
}
return board;
}
void dfs(vector<vector<char>>& board,int x,int y){
int cnt=0;
for(int i=0;i<8;i++){
int xx=x+dx[i];
int yy=y+dy[i];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&board[xx][yy]=='M'){
cnt++;
}
}
if(cnt>0){
board[x][y]=cnt+'0';
}else{
board[x][y]='B';
for(int i=0;i<8;i++){
int xx=x+dx[i];
int yy=y+dy[i];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&board[xx][yy]=='E'){
dfs(board,xx,yy);
}
}
}
}
};