写在前面
这道题和200. 岛屿数量很像,只不过200. 岛屿数量是求岛屿总个数,这道题是求最大的岛屿面积,基本代码逻辑是一样的,只不过具体处理细节有一点不一样
思路
在主函数maxAreaOfIsland
中遍历,遇到岛屿temp
就计数为1,然后进入dfs
函数,每次遍历到一个岛屿,temp
就加1,用变量temp
记录此时这个岛屿的面积,用result
记录最后结果,如果temp
大于result
,那么更新result
话不多说上代码
class Solution {
boolean[][] used;
int temp = 0;
public void dfs(int[][] grid, int x, int y) {
int[][] directions = new int[][]{
{1, 0}, {0, 1}, {-1, 0}, {0, -1}
};
for (int i = 0; i < 4; i++) {
int nextX = x + directions[i][0];
int nextY = y + directions[i][1];
if (nextX < 0 || nextX >= grid.length || nextY < 0 || nextY >= grid[0].length) {
continue;
}
if (!used[nextX][nextY] && grid[nextX][nextY] == 1) {
temp++;
used[nextX][nextY] = true;
dfs(grid, nextX, nextY);
}
}
}
public int maxAreaOfIsland(int[][] grid) {
used = new boolean[grid.length][grid[0].length];
int result = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (!used[i][j] && grid[i][j] == 1) {
temp = 1;
used[i][j] = true;
dfs(grid, i, j);
result = Math.max(result, temp);
}
}
}
return result;
}
}
标签:temp,695,int,力扣,Day59,grid,result,nextX,nextY
From: https://www.cnblogs.com/BearFishSheep/p/17787942.html