Skip to content

Commit 4bc906e

Browse files
authored
Update surrounded-regions.cpp
1 parent 0b0bb68 commit 4bc906e

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

C++/surrounded-regions.cpp

+27-19
Original file line numberDiff line numberDiff line change
@@ -10,34 +10,42 @@ class Solution {
1010

1111
queue<pair<int, int>> q;
1212
for (int i = 0; i < board.size(); ++i) {
13-
q.emplace(i, 0);
14-
q.emplace(i, board[0].size() - 1);
15-
}
16-
for (int j = 0; j < board[0].size(); ++j) {
17-
q.emplace(0, j);
18-
q.emplace(board.size() - 1, j);
13+
if (board[i][0] == 'O') {
14+
board[i][0] = 'V';
15+
q.emplace(i, 0);
16+
}
17+
if (board[i][board[0].size() - 1] == 'O') {
18+
board[i][board[0].size() - 1] = 'V';
19+
q.emplace(i, board[0].size() - 1);
20+
}
1921
}
2022

23+
for (int j = 1; j < board[0].size() - 1; ++j) {
24+
if (board[0][j] == 'O') {
25+
board[0][j] = 'V';
26+
q.emplace(0, j);
27+
}
28+
if (board[board.size() - 1][j] == 'O') {
29+
board[board.size() - 1][j] = 'V';
30+
q.emplace(board.size() - 1, j);
31+
}
32+
}
2133
while (!q.empty()) {
2234
int i, j;
2335
tie(i, j) = q.front();
2436
q.pop();
25-
if (board[i][j] == 'O' || board[i][j] == 'V') {
26-
board[i][j] = 'V';
27-
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
28-
{-1, 0}, {1, 0}};
29-
for (const auto& d : directions) {
30-
const int x = i + d.first, y = j + d.second;
31-
if (0 <= x && x < board.size() &&
32-
0 <= y && y < board[0].size() &&
33-
board[x][y] == 'O') {
34-
board[x][y] = 'V';
35-
q.emplace(x, y);
36-
}
37+
static const vector<pair<int, int>> directions{{0, -1}, {0, 1},
38+
{-1, 0}, {1, 0}};
39+
for (const auto& d : directions) {
40+
const int x = i + d.first, y = j + d.second;
41+
if (0 <= x && x < board.size() &&
42+
0 <= y && y < board[0].size() &&
43+
board[x][y] == 'O') {
44+
board[x][y] = 'V';
45+
q.emplace(x, y);
3746
}
3847
}
3948
}
40-
4149
for (int i = 0; i < board.size(); ++i) {
4250
for (int j = 0; j < board[0].size(); ++j) {
4351
if (board[i][j] != 'V') {

0 commit comments

Comments
 (0)