-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path130. Surrounded Regions.cpp
65 lines (42 loc) · 1.24 KB
/
130. 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
60
61
62
63
64
65
class Solution {
int x[4] = {-1,1,0,0};
int y[4] = {0,0,-1,1};
void dfs(vector<vector<char>>& board, int i , int j) {
board[i][j] = '?';
int n = board.size();
int m = board[0].size();
for(int k = 0;k < 4; ++k) {
int newx = i+x[k];
int newy = j+y[k];
if (newx > 0 && newy > 0 && (newx < n-1) && (newy < m-1) && board[newx][newy] == 'O')
dfs(board,newx,newy);
}
}
public:
void solve(vector<vector<char>>& board) {
if (board.empty())
return;
int n = board.size();
int m = board[0].size();
for(int i = 0;i<n;++i) {
if(board[i][0] == 'O')
dfs(board, i,0);
if(board[i][m-1] == 'O')
dfs(board, i,m-1);
}
for(int j = 1;j<m-1;++j){
if(board[0][j] == 'O')
dfs(board, 0,j);
if(board[n-1][j] == 'O')
dfs(board, n-1,j);
}
for(int i = 0;i<n;++i)
for(int j = 0;j<m;++j) {
if(board[i][j] == '?')
board[i][j] = 'O';
else
board[i][j] = 'X';
}
return;
}
};