-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ200.java
More file actions
42 lines (41 loc) · 1.37 KB
/
Q200.java
File metadata and controls
42 lines (41 loc) · 1.37 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
/*
* @Author: Shawn Yang
* @Date: 2019-09-10 12:35:01
* @Last Modified by: Shawn Yang
* @Last Modified time: 2019-09-10 13:10:48
*/
class Solution {
public int maxRow;
public int maxColumn;
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
maxRow = grid.length;
maxColumn = grid[0].length;
boolean[][] visited = new boolean[maxRow][maxColumn];
int result = 0;
for(int i = 0; i < maxRow; i++) {
for(int j = 0; j < maxColumn; j++) {
if(visited[i][j] || grid[i][j] == '0') {
continue;
} else {
result += 1;
dfsHelper(visited, i, j, grid);
}
}
}
return result;
}
public void dfsHelper(boolean[][] visited, int row, int column, char[][] grid) {
if(row < 0 || column < 0 || row >= maxRow || column >= maxColumn || visited[row][column] == true || grid[row][column] == '0') {
return;
} else {
visited[row][column] = true;
dfsHelper(visited, row + 1, column, grid);
dfsHelper(visited, row, column + 1, grid);
dfsHelper(visited, row - 1, column, grid);
dfsHelper(visited, row, column - 1, grid);
}
}
}