-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSurroundedRegion.java
More file actions
95 lines (76 loc) · 1.58 KB
/
SurroundedRegion.java
File metadata and controls
95 lines (76 loc) · 1.58 KB
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
92
93
94
95
import java.util.*;
public class SurroundedRegion {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void solve(char[][] board) {
if(board.length ==0) return;
int m = board.length;
int n = board[0].length;
for(int i = 0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(i==0||i==m-1||j==0||j==n-1){
dfs(board, i, j, m, n);
}
}
}
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(board[i][j] == 'o')
{
board[i][j] = 'O';
}
else
{
board[i][j] = 'X';
}
}
}
}
public void dfs(char board[][], int i, int j, int m, int n)
{
LinkedList<point> stack = new LinkedList<point>();
stack.push(new point(i,j));
while(stack.size()!=0)
{
point p = stack.pop();
if(board[p.x][p.y] == 'O')
{
board[p.x][p.y] = 'o';
if(p.x -1 >=0 && board[p.x-1][p.y] == 'O')
{
stack.push(new point(p.x-1, p.y));
}
if(p.y -1 >=0 && board[p.x][p.y-1] == 'O')
{
stack.push(new point(p.x, p.y-1));
}
if(p.x +1 <m && board[p.x+1][p.y] == 'O')
{
stack.push(new point(p.x+1, p.y));
}
if(p.y +1 <n && board[p.x][p.y+1] == 'O')
{
stack.push(new point(p.x, p.y+1));
}
}
}
}
class point
{
public int x;
public int y;
public point(int x, int y)
{
this.x = x;
this.y = y;
}
}
}