[LeetCode] Minesweeper

529. Minesweeper

Let’s play the minesweeper game (Wikipedia, online game)!

You are given an m x n char matrix board representing the game board where:

  • ‘M’ represents an unrevealed mine,
  • ‘E’ represents an unrevealed empty square,
  • ‘B’ represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
  • digit (‘1’ to ‘8’) represents how many mines are adjacent to this revealed square, and
  • ‘X’ represents a revealed mine.

You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares (‘M’ or ‘E’).

Return the board after revealing this position according to the following rules:

  1. If a mine ‘M’ is revealed, then the game is over. You should change it to ‘X’.
  2. If an empty square ‘E’ with no adjacent mines is revealed, then change it to a revealed blank ‘B’ and all of its adjacent unrevealed squares should be revealed recursively.
  3. 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.
  4. Return the board when no more squares will be revealed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& b, vector<int>& c) {
char& t = b[c.front()][c.back()];
if(isdigit(t) || t == 'B' || t == 'X') return b;
if(t == 'M') {t = 'X'; return b;}
queue<pair<int, int>> q;
int dx[8]{-1,0,1,1,1,0,-1,-1}, dy[8]{-1,-1,-1,0,1,1,1,0}, m = b[0].size(), n = b.size();
q.push({c.front(), c.back()});
while(!q.empty()) {
auto p = q.front();
q.pop();
if(b[p.first][p.second] != 'E') continue;
char open = '0';
for(int i = 0; i < 8; i++) {
int ny = p.first + dy[i], nx = p.second + dx[i];
if(0 <= ny && ny < n && 0 <= nx && nx < m && (b[ny][nx] == 'M' || b[ny][nx] == 'X')) open++;
}
if(open != '0') b[p.first][p.second] = open;
else {
b[p.first][p.second] = 'B';
for(int i = 0; i < 8; i++) {
int ny = p.first + dy[i], nx = p.second + dx[i];
if(0 <= ny && ny < n && 0 <= nx && nx < m && b[ny][nx] == 'E') q.push({ny,nx});
}
}
}
return b;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/23/PS/LeetCode/minesweeper/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.