4. 岛屿的最大面积(中等)
地址: https://leetcode-cn.com/problems/max-area-of-island/
2022/01/27
做题反思:
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int res = 0;
int m = grid.length, n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
res = Math.max(res, dfs(grid, i, j));
}
}
}
return res;
}
int dfs(int[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
return 0;
}
if (grid[i][j] == 0) {
return 0;
}
grid[i][j] = 0;
return dfs(grid, i, j - 1) +
dfs(grid, i, j + 1) +
dfs(grid, i - 1, j) +
dfs(grid, i + 1, j) + 1;
}
}
5. 统计子岛屿(中等)
地址: https://leetcode-cn.com/problems/count-sub-islands/
2022/01/27
做题反思:
class Solution {
public int countSubIslands(int[][] grid1, int[][] grid2) {
int res = 0;
int m = grid1.length, n = grid1[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid1[i][j] == 0 && grid2[i][j] == 1) {
dfs(grid2, i, j);
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid2[i][j] == 1) {
res++;
dfs(grid2, i, j);
}
}
}
return res;
}
void dfs(int[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
return;
}
if (grid[i][j] == 0) {
return;
}
grid[i][j] = 0;
dfs(grid, i, j + 1);
dfs(grid, i, j - 1);
dfs(grid, i - 1, j);
dfs(grid, i + 1, j);
}
}
6. 不同的岛屿数量(中等)
地址vip题: https://leetcode-cn.com/problems/number-of-distinct-islands/
地址: https://labuladong.gitee.io/algo/1/9/
2022/
做题反思: