leetcode200
3/2/2021 算法dfs
# 解题思路
去年没写出来的每日一题,今年来还愿
# 代码
class Solution {
public int numIslands(char[][] grid) {
int m = grid.length;
int n = grid[0].length;
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
++ans;
dfs(grid, i, j, ans);
}
}
}
return ans;
}
public int dfs(char[][] grid, int i, int j, int ans) {
grid[i][j] = (char) (ans+'1');
if (i > 0 && grid[i - 1][j] == '1') {
grid[i - 1][j] = grid[i][j];
dfs(grid, i - 1, j, ans);
}
if (j > 0 && grid[i][j - 1] == '1') {
grid[i][j - 1] = grid[i][j];
dfs(grid, i , j-1, ans);
}
if (i +1 < grid.length && grid[i + 1][j] == '1') {
grid[i + 1][j] = grid[i][j];
dfs(grid, i + 1, j, ans);
}
if (j +1 < grid[0].length && grid[i][j+1] == '1') {
grid[i][j+1] = grid[i][j];
dfs(grid, i , j+1, ans);
}
return ans;
}
}
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
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