[LeetCode] Surrounded Regions

130. Surrounded Regions

Given a 2D board containing ‘X’ and ‘O’ (the letter O), capture all regions surrounded by ‘X’.

A region is captured by flipping all ‘O’s into ‘X’s in that surrounded region.

Example:

1
2
3
4
X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

1
2
3
4
X X X X
X X X X
X X X X
X O X X

Explanation:

Surrounded regions shouldn’t be on the border, which means that any ‘O’ on the border of the board are not flipped to ‘X’. Any ‘O’ that is not on the border and it is not connected to an ‘O’ on the border will be flipped to ‘X’. Two cells are connected if they are adjacent cells connected horizontally or vertically.

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
class Solution {
public:
void solve(vector<vector<char>>& board) {
if(board.empty() || board[0].empty())
return;
int h = board.size(), w = board[0].size();
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
vector<vector<bool>> isVisited(h, std::vector<bool>(w, false));
queue<pair<int, int>> q;

for(int i = 0; i < w; i++) {
if(board[0][i] == 'O') {
isVisited[0][i] = true;
q.push({0,i});
}
if(board[h - 1][i] == 'O') {
isVisited[h - 1][i] = true;
q.push({h - 1, i});
}
}

for(int i = 1; i < h; i++) {
if(board[i][0] == 'O') {
isVisited[i][0] = true;
q.push({i, 0});
}
if(board[i][w - 1] == 'O') {
isVisited[i][w - 1] = true;
q.push({i, w - 1});
}
}

while(!q.empty()) {
auto p = q.front();
q.pop();
for(int i = 0; i < 4; i++) {
int nx = p.second + dx[i];
int ny = p.first + dy[i];
if(0 <= nx && nx < w && 0 <= ny && ny < h && !isVisited[ny][nx] && board[ny][nx] == 'O') {
q.push({ny, nx});
isVisited[ny][nx] = true;
}
}
}

for(int i = 0; i < h; i++) {
for(int j = 0; j < w; j++) {
if(!isVisited[i][j])
board[i][j] = 'X';
}
}

return;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/26/PS/LeetCode/surrounded-regions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.