-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode_200.java
32 lines (28 loc) · 1.07 KB
/
LeetCode_200.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
public class LeetCode_200 {
class Solution {
public int numIslands(char[][] grid) {
int res = 0;
int index = 1;
int[][] visited = new int[grid.length][grid[0].length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1' && visited[i][j] == 0) {
dfs(grid, visited, i, j, index ++);
res = Math.max(res, visited[i][j]);
}
}
}
return res;
}
public void dfs(char[][] grid, int[][] visited, int i, int j, int index) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == '0' || visited[i][j] != 0) {
return;
}
visited[i][j] = index;
dfs(grid, visited, i + 1, j, index);
dfs(grid, visited, i - 1, j, index);
dfs(grid, visited, i, j + 1, index);
dfs(grid, visited, i, j - 1, index);
}
}
}