forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minesweeper.cpp
108 lines (102 loc) · 3.72 KB
/
minesweeper.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Time: O(m * n)
// Space: O(m + n)
class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
queue<vector<int>> q;
q.emplace(click);
while (!q.empty()) {
int row = q.front()[0], col = q.front()[1];
q.pop();
if (board[row][col] == 'M') {
board[row][col] = 'X';
} else {
int count = 0;
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (i == 0 && j == 0) {
continue;
}
int r = row + i, c = col + j;
if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) {
continue;
}
if (board[r][c] == 'M' || board[r][c] == 'X') {
++count;
}
}
}
if (count > 0) {
board[row][col] = count + '0';
} else {
board[row][col] = 'B';
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (i == 0 && j == 0) {
continue;
}
int r = row + i, c = col + j;
if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) {
continue;
}
if (board[r][c] == 'E') {
vector<int> next_click = {r, c};
q.emplace(next_click);
board[r][c] = 'B';
}
}
}
}
}
}
return board;
}
};
// Time: O(m * n)
// Space: O(m * n)
class Solution2 {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int row = click[0], col = click[1];
if (board[row][col] == 'M') {
board[row][col] = 'X';
} else {
int count = 0;
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (i == 0 && j == 0) {
continue;
}
int r = row + i, c = col + j;
if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) {
continue;
}
if (board[r][c] == 'M' || board[r][c] == 'X') {
++count;
}
}
}
if (count > 0) {
board[row][col] = count + '0';
} else {
board[row][col] = 'B';
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (i == 0 && j == 0) {
continue;
}
int r = row + i, c = col + j;
if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) {
continue;
}
if (board[r][c] == 'E') {
vector<int> next_click = {r, c};
updateBoard(board, next_click);
}
}
}
}
}
return board;
}
};