forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
surrounded-regions.cpp
59 lines (56 loc) · 1.8 KB
/
surrounded-regions.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
// Time: O(m * n)
// Space: O(m + n)
class Solution {
public:
void solve(vector<vector<char>>& board) {
if (board.empty()) {
return;
}
queue<pair<int, int>> q;
for (int i = 0; i < board.size(); ++i) {
if (board[i][0] == 'O') {
board[i][0] = 'V';
q.emplace(i, 0);
}
if (board[i][board[0].size() - 1] == 'O') {
board[i][board[0].size() - 1] = 'V';
q.emplace(i, board[0].size() - 1);
}
}
for (int j = 1; j < board[0].size() - 1; ++j) {
if (board[0][j] == 'O') {
board[0][j] = 'V';
q.emplace(0, j);
}
if (board[board.size() - 1][j] == 'O') {
board[board.size() - 1][j] = 'V';
q.emplace(board.size() - 1, j);
}
}
while (!q.empty()) {
int i, j;
tie(i, j) = q.front();
q.pop();
static const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
for (const auto& d : directions) {
const int x = i + d.first, y = j + d.second;
if (0 <= x && x < board.size() &&
0 <= y && y < board[0].size() &&
board[x][y] == 'O') {
board[x][y] = 'V';
q.emplace(x, y);
}
}
}
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
if (board[i][j] != 'V') {
board[i][j] = 'X';
} else {
board[i][j] = 'O';
}
}
}
}
};