827 最大人工岛

hard题目,十分困难哈,不是简单的岛屿套路,而是要经历过两次遍历,先一次遍历岛屿再一次遍历海洋

题目

给你一个大小为 n x n 二进制矩阵 grid最多 只能将一格 0 变成 1

返回执行此操作后,grid 中最大的岛屿面积是多少?

岛屿 由一组上、下、左、右四个方向相连的 1 形成。

示例 1:

lua 复制代码
输入: grid = [[1, 0], [0, 1]]
输出: 3
解释: 将一格0变成1,最终连通两个小岛得到面积为 3 的岛屿。

代码与解析

java 复制代码
class Solution {
    int n;
    Map<Integer, Integer> map = new HashMap<>();

    public int largestIsland(int[][] grid) {
        n = grid.length;
        int ans = 0;
        int index = 2;

        // 遍历整个 grid,标记陆地并计算各个岛屿的面积
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    int t = land(grid, i, j, index); // 标记岛屿并计算面积
                    map.put(index, t); // 将岛屿编号和面积存入 map
                    index++;
                    ans = Math.max(ans, t); // 更新最大岛屿面积
                }
            }
        }

        // 处理全海洋情况
        if (ans == 0) return 1;

        // 遍历海洋区域,寻找合并后的最大岛屿面积
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 0) {
                    HashSet<Integer> set = findNeighbor(grid, i, j); // 找到相邻岛屿
                    if (set.size() < 1) continue; // 若无相邻岛屿,则跳过
                    int t = 1;
                    for (Integer m : set) t += map.get(m); // 计算合并后的岛屿面积
                    ans = Math.max(ans, t); // 更新最大岛屿面积
                }
            }
        }
        return ans;
    }

    // 查找相邻的岛屿
    public HashSet<Integer> findNeighbor(int[][] grid, int x, int y) {
        HashSet<Integer> set = new HashSet<>();
        if (!notarea(x - 1, y) && grid[x - 1][y] != 0) set.add(grid[x - 1][y]);
        if (!notarea(x + 1, y) && grid[x + 1][y] != 0) set.add(grid[x + 1][y]);
        if (!notarea(x, y - 1) && grid[x][y - 1] != 0) set.add(grid[x][y - 1]);
        if (!notarea(x, y + 1) && grid[x][y + 1] != 0) set.add(grid[x][y + 1]);
        return set;
    }

    // 标记岛屿并计算面积
    public int land(int[][] grid, int x, int y, int index) {
        if (notarea(x, y) || grid[x][y] == 0) return 0;
        if (grid[x][y] != 1) return 0;
        grid[x][y] = index;
        int region = land(grid, x, y + 1, index) + land(grid, x, y - 1, index)
                + land(grid, x + 1, y, index) + land(grid, x - 1, y, index);
        return region + 1;
    }

    // 判断是否超出边界
    public boolean notarea(int x, int y) {
        return x < 0 || y < 0 || x >= n || y >= n;
    }
}
相关推荐
ai小鬼头1 小时前
百度秒搭发布:无代码编程如何让普通人轻松打造AI应用?
前端·后端·github
考虑考虑1 小时前
@FilterRegistration和@ServletRegistration注解
spring boot·后端·spring
一只叫煤球的猫1 小时前
🔥 同事混用@Transactional和TransactionTemplate被我怼了,三种事务管理到底怎么选?
java·spring boot·后端
你的人类朋友9 天前
(●'◡'●)从Dockerfile快速入门Docker Compose
后端
GetcharZp9 天前
「神器推荐」Rclone:轻松玩转云端存储,FTP 也能飞起来!
后端
华子w9089258599 天前
基于 SpringBoot+JSP 的医疗预约与诊断系统设计与实现
java·spring boot·后端
舒一笑9 天前
工作流会使用到Webhook是什么
后端·程序员
止观止9 天前
Rust智能指针演进:从堆分配到零复制的内存管理艺术
开发语言·后端·rust
学無芷境9 天前
Cargo 与 Rust 项目
开发语言·后端·rust
ai小鬼头9 天前
AIStarter开发者熊哥分享|低成本部署AI项目的实战经验
后端·算法·架构