Day59 | 力扣695:岛屿的最大面积

力扣链接

写在前面

这道题和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;
    }
}
posted @ 2023-10-25 19:15  布布布丁  阅读(45)  评论(0)    收藏  举报