Minesweeper
Thoughts
Code
class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
queue<pair<int, int>> q;
auto x = click[0], y = click[1];
if (board[x][y] == 'M') {
board[x][y] = 'X';
} else {
q.emplace(x, y);
}
const auto m = board.size(), n = board[0].size();
while (!q.empty()) {
const auto size = q.size();
for (int i = 0; i < size; ++i) {
const auto p = q.front(); q.pop();
int cur_x = p.first, cur_y = p.second;
if (board[cur_x][cur_y] != 'E') continue;
int count = 0;
vector<pair<int, int>> tmp;
for (int j = -1; j <= 1; ++j) {
for (int k = -1; k <= 1; ++k) {
x = cur_x + j;
y = cur_y + k;
if (x >= 0 && x < m && y >= 0 && y < n) {
if (board[x][y] == 'M') ++count;
tmp.emplace_back(x, y);
}
}
}
if (count) {
board[cur_x][cur_y] = '0' + count;
} else {
board[cur_x][cur_y] = 'B';
for (const auto p : tmp) {
q.push(p);
}
}
}
}
return board;
}
};Analysis
Last updated