1 题目分析
题目链接:点击打开链接
题目就是小时候玩过的扫雷游戏,总结一下规则,在本题中规则也就是思路了:
① 扫到M → 用X替换M,游戏结束(返回board)
② 扫到E → 计算其周围(8个方向)的M的个数Mcount
→ Mcount > 0,用Mcount替换E
→ Mcount = 0,用B替换E → 翻开其周围的方格(处理一下处于边界的位置,对该位置的8个邻居方格递归调用函数)
上述思路的思想是DFS,实现见下述代码一。
如果为了方便实现,可以用一个neighbors的向量在循环周围8个位置时将满足 board == 'E' && Mcount == 0 的条件位置信息存下来,并在后面再统一对其进行递归调用。这样的思想就变成了BFS(这是看discussion中意识到的),实现见下述代码二。
2 代码 C++
DFS方法,感觉自己这个实现的过程代码有些冗余。
class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int cRow = click[0],
cCol = click[1];
int Mcount = 0;
if(board[cRow][cCol] == 'M') {
board[cRow][cCol] = 'X';
return board;
}
else {
for(int i = -1; i < 2; i++)
for(int j = -1; j < 2; j++) {
if(cRow + i < 0 || cRow + i >= board.size() || cCol + j < 0 || cCol + j >= board[0].size())
continue;
if(board[cRow + i][cCol + j] == 'M')
Mcount++;
}
if(Mcount > 0)
board[cRow][cCol] = Mcount + '0';
else {
board[cRow][cCol] = 'B';
for(int i = -1; i < 2; i++)
for(int j = -1; j < 2; j++) {
if(cRow + i < 0 || cRow + i >= board.size() || cCol + j < 0 || cCol + j >= board[0].size())
continue;
if(board[cRow + i][cCol + j] == 'E') {
vector<int> next{cRow + i, cCol + j};
updateBoard(board, next);
}
}
}
}
return board;
}
};
BFS方法:
class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int cRow = click[0],
cCol = click[1];
int Mcount = 0;
if(board[cRow][cCol] == 'M') {
board[cRow][cCol] = 'X';
return board;
}
else {
vector<vector<int>> neighbors;
for(int i = -1; i < 2; i++) {
for(int j = -1; j < 2; j++) {
if(cRow + i < 0 || cRow + i >= board.size() || cCol + j < 0 || cCol + j >= board[0].size())
continue;
if(board[cRow + i][cCol + j] == 'M')
Mcount++;
else if(Mcount == 0 && board[cRow + i][cCol + j] == 'E')
neighbors.push_back({cRow + i, cCol + j});
}
}
if(Mcount > 0)
board[cRow][cCol] = Mcount + '0';
else {
for(auto a : neighbors) {
board[a[0]][a[1]] = 'B';
updateBoard(board, a);
}
}
}
return board;
}
};
附上discussion里的一个答案和讨论:点击打开链接