-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCode07NumbersOfIsland.java
More file actions
48 lines (39 loc) · 1.34 KB
/
Code07NumbersOfIsland.java
File metadata and controls
48 lines (39 loc) · 1.34 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
package com.leecode.tree;
public class Code07NumbersOfIsland {
void dfs(char[][] grid, int r, int c) {
int nr = grid.length;
int nc = grid[0].length;
if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') {
return;
}
grid[r][c] = '0';
dfs(grid, r - 1, c);
dfs(grid, r + 1, c);
dfs(grid, r, c - 1);
dfs(grid, r, c + 1);
}
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int nr = grid.length;
int nc = grid[0].length;
int num_islands = 0;
for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
if (grid[r][c] == '1') {
++num_islands;
dfs(grid, r, c);
}
}
}
return num_islands;
}
public static void main(String[] args) {
char[][] a = {{'1','1','0','0','0'},{'1','1','0','0','0'},{'0','0','1','0','0'},{'0','0','0','1','1'}};
// char[][] a = {{'1','1','1','1','1'},{'1','1','1','1','1'},{'1','1','1','1','1'},{'0','0','0','1','1'}};
Code07NumbersOfIsland c=new Code07NumbersOfIsland();
int an=c.numIslands(a);
System.out.println(an);
}
}