forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0130-surrounded-regions.cpp
52 lines (44 loc) · 1.32 KB
/
0130-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
/*
Given a matrix, capture ('X') all regions that are surrounded ('O')
Distinguish captured vs escaped, 'X' vs 'O' vs 'E'
Time: O(m x n)
Space: O(m x n)
*/
class Solution {
public:
void solve(vector<vector<char>>& board) {
int m = board.size();
int n = board[0].size();
// marking escaped cells along the border
for (int i = 0; i < m; i++) {
dfs(board,i,0,m,n);
dfs(board,i,n-1,m,n);
}
for (int j = 0; j < n; j++) {
dfs(board,0,j,m,n);
dfs(board,m-1,j,m,n);
}
// flip cells to correct final states
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}
if (board[i][j] == 'E') {
board[i][j] = 'O';
}
}
}
}
private:
void dfs(vector<vector<char>>& board, int i, int j, int m, int n) {
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') {
return;
}
board[i][j] = 'E';
dfs(board, i - 1, j, m, n);
dfs(board, i + 1, j, m, n);
dfs(board, i, j - 1, m, n);
dfs(board, i, j + 1, m, n);
}
};