-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
38 lines (31 loc) · 819 Bytes
/
Copy pathSolution.java
File metadata and controls
38 lines (31 loc) · 819 Bytes
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
class Solution {
public int numIslands(char[][] grid) {
int n = grid.length;
int m = grid[0].length;
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1') {
count++;
flip(i, j, grid);
}
}
}
return count;
}
private void flip(int i, int j, char[][] grid) {
int n = grid.length;
int m = grid[0].length;
if (i >= n || j >= m || i < 0 || j < 0) {
return;
}
if (grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
flip(i + 1, j, grid);
flip(i - 1, j, grid);
flip(i, j + 1, grid);
flip(i, j - 1, grid);
}
}