-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathSurroundedRegions.java
91 lines (67 loc) · 1.22 KB
/
SurroundedRegions.java
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class Solution {
private class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public void solve(char[][] board) {
if(board.length==0 || board[0].length==0){
return ;
}
int n = board.length;
int m = board[0].length;
// first column
for(int i=0;i<n;i++){
if(board[i][0] =='O'){
dfs(board, i, 0);
}
}
// last column
for(int i=0;i<n;i++){
if(board[i][m-1] =='O'){
dfs(board, i, m-1);
}
}
// first row
for(int i=0;i<m;i++){
if(board[0][i] =='O'){
dfs(board, 0,i);
}
}
// last row
for(int i=0;i<m;i++){
if(board[n-1][i] =='O'){
dfs(board, n-1,i);
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(board[i][j] =='O'){
board[i][j] = 'X';
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(board[i][j] =='V'){
board[i][j] = 'O';
}
}
}
}
private void dfs(char[][] baord, int i , int j){
if(i<0 || j<0 || i>=baord.length || j>=baord[0].length || (baord[i][j] == 'V') || (baord[i][j] == 'X')){
return ;
}
else {
baord[i][j] = 'V';
dfs(baord, i-1, j);
dfs(baord, i+1, j);
dfs(baord, i, j-1);
dfs(baord, i, j+1);
}
}
}