-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path130-surrounded-regions.cpp
60 lines (55 loc) · 1.6 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
class Solution {
bool seen;
void mark(vector<vector<char>>& board,int i,int j,int r,int c)
{
if(i<0 || i>r-1 || j<0 || j>c-1)
return;
if(board[i][j]=='X')
return;
board[i][j] = 'X';
mark(board,i-1,j,r,c);
mark(board,i+1,j,r,c);
mark(board,i,j-1,r,c);
mark(board,i,j+1,r,c);
}
void dfs(vector<vector<char>>& board,int i,int j,int r,int c,vector<vector<bool>>& visited)
{
if(i<0 || i>r-1 || j<0 || j>c-1)
return;
if(board[i][j]=='X' || visited[i][j])
return;
if(i<=0 || i>=r-1 || j<=0 || j>=c-1)
seen = true;
visited[i][j] = true;
dfs(board,i-1,j,r,c,visited);
dfs(board,i+1,j,r,c,visited);
dfs(board,i,j-1,r,c,visited);
dfs(board,i,j+1,r,c,visited);
}
public:
void solve(vector<vector<char>>& board) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int r=board.size();
if(r<=1)
return;
int c=board[0].size();
if(c<=1)
return;
vector<vector<bool>> visited(r,vector<bool>(c,false));
for(int i=1;i<r-1;++i)
{
for(int j=1;j<c-1;++j)
{
if(board[i][j]=='O' && !visited[i][j])
{
seen = false;
dfs(board,i,j,r,c,visited);
if(seen==false)
mark(board,i,j,r,c);
seen = true;
}
}
}
}
};