-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumber_of_islands.java
More file actions
103 lines (78 loc) · 2.43 KB
/
Copy pathnumber_of_islands.java
File metadata and controls
103 lines (78 loc) · 2.43 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
96
97
98
99
100
101
102
103
class Solution {
public static class point
{
int x;
int y;
point(int x,int y)
{
this.x = x;
this.y=y;
}
}
static boolean checkb(int i,int j,int rl,int cl)
{
return ((i>=0 && i<rl)&&(j>=0 && j<cl)) ? true:false;
}
static void bfs(char[][] grid,boolean[][] m,int i,int j)
{
ArrayList<point> q = new ArrayList<point>();
point st = new point(i,j);
q.add(st);
while(!q.isEmpty())
{
point curr = q.get(0);
q.remove(0);
m[curr.x][curr.y] = true;
int li =curr.x-1,lj=curr.y,ri=curr.x+1,rj=curr.y,ui=curr.x,uj=curr.y+1,di=curr.x,dj=curr.y-1;
if(checkb(li,lj,grid.length,grid[0].length))
{
if(!m[li][lj] && grid[li][lj]=='1')
{point l = new point(li,lj);
q.add(l);
}
}
if(checkb(ri,rj,grid.length,grid[0].length))
{
if(!m[ri][rj] && grid[ri][rj]=='1')
{point r = new point(ri,rj);
q.add(r);
}
}
if(checkb(ui,uj,grid.length,grid[0].length))
{
if(!m[ui][uj] && grid[ui][uj]=='1')
{point u = new point(ui,uj);
q.add(u);
}
}
if(checkb(di,dj,grid.length,grid[0].length))
{
if(!m[di][dj] && grid[di][dj]=='1' )
{
point d = new point(di,dj);
q.add(d);
}
}
}
}
public int numIslands(char[][] grid) {
if(grid.length == 0)
{
return 0;
}
boolean[][] m = new boolean[grid.length][grid[0].length];
int ans=0;
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[0].length;j++)
{
if(grid[i][j] =='1' && !m[i][j])
{
++ans;
bfs(grid,m,i,j);
}
}
}
return ans;
}
}