思路:dfs,当某一个是1的时候,在dfs中将其改为0然后尝试所有方向
// @Title: 岛屿的最大面积 (Max Area of Island)
// @Author: qisiii
// @Date: 2024-01-14 21:25:40
// @Runtime: 2 ms
// @Memory: 43.1 MB
// @comment: dfs,当某一个是1的时候,在dfs中将其改为0然后尝试所有方向
// @flag: GREEN
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int x = 0, y = 0, max = 0;
while (x < grid.length) {
y=0;
while (y < grid[x].length) {
Integer size = 0;
if (grid[x][y] == 1) {
size = dfs(x, y, grid);
max = Math.max(max, size);
}
y++;
}
x++;
}
return max;
}
int dfs(int x, int y, int[][] grid) {
int i = 0;
if (x >= grid.length || x < 0 || y >= grid[x].length || y < 0) {
return 0;
}
if (grid[x][y] == 1) {
i = 1;
} else {
return 0;
}
grid[x][y] = 0;
i += dfs(x, y + 1, grid);
i += dfs(x + 1, y, grid);
i += dfs(x, y - 1, grid);
i += dfs(x - 1, y, grid);
return i;
}
}