leetcode695. 岛屿的最大面积

文章提供了一段Java代码,用于解决695.岛屿的最大面积问题。通过深度优先搜索(DFS)算法,遍历二维数组网格,寻找并计算1(代表陆地)形成的岛屿的最大面积。
摘要由CSDN通过智能技术生成

牛客华为机试题库【题号 HJ开头】(重点看)
牛客在线编程算法篇【题号NC开头】
剑指offer【题号 JZ开头】
力扣

1)原题链接

2)已有题解

3)代码

package dfs;

import java.io.IOException;

/**
 * 695. 岛屿的最大面积
 */
public class Leetcode695MaxAreaOfIsland {
    public static void main(String[] args) throws IOException {
        int[][] grid = {{0, 0, 1}, {0, 0, 1}, {0, 0, 1}};
        Leetcode695MaxAreaOfIsland leetcode695MaxAreaOfIsland = new Leetcode695MaxAreaOfIsland();
        leetcode695MaxAreaOfIsland.maxAreaOfIsland(grid);
    }

    public int maxAreaOfIsland(int[][] grid) {
        int max = 0; // 如果没有岛屿,则返回面积为 0

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == 1) { // 找到一个1就会把接壤的所有1都标记成2,然后遍历完这个岛屿
                    int islandArea = dfs(grid, i, j); // 当前岛屿的面积
                    max = Math.max(max, islandArea); // 动态算出最大面积
                }
            }
        }

        return max;
    }

    public int dfs(int[][] grid, int row, int column) {
        if (!isInGrid(grid, row, column)) {
            return 0; // 不在网格内
        }

        if (grid[row][column] == 0) {
            return 0; // '0'(水)
        }

        if (grid[row][column] == 2) {
            return 0; // 走过的地方
        }

        grid[row][column] = 2; // 每走过一个陆地格子,就把格子的值改为 2,防止走到重复的地方去

        // 当前节点面积+上、下、左、右四个相邻结点引申出去计算得到的面积
        return 1 + dfs(grid, row - 1, column)
                + dfs(grid, row + 1, column)
                + dfs(grid, row, column - 1)
                + dfs(grid, row, column + 1);
    }

    private boolean isInGrid(int[][] grid, int row, int column) {
        return 0 <= row && row < grid.length && 0 <= column && column < grid[row].length;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值