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;
    }
}
相关推荐
心运软件20 分钟前
SpringBoot+ Vue校园社团管理平台的完整架构设计
vue.js·后端
Jodie同志1 小时前
第16~23天:持久化、HITL、流式、MCP与安全
前端·后端·agent
Jodie同志1 小时前
第1~15天:原生Agent、RAG与LangGraph基础(完整代码实操)
前端·后端·agent
Zane19941 小时前
单例线程安全、生产者消费者、死锁:并发面试三连问串讲
java·后端
用户69371750013841 小时前
#DeepSeek+Pi‑Agent 王炸组合跑赢 Claude‑Code!
前端·人工智能·后端
Zane19941 小时前
类变量与实例变量:一个共享列表引发的线上事故
后端·python
Scene2162 小时前
AgentScope 2.0:2. 快速上手 从零构建生产级智能体
后端
前端一课2 小时前
用 TRAE Work 把项目踩坑经验沉淀成「团队可复用工程规范」,新人再也不重复掉坑
前端·后端
神奇小汤圆2 小时前
一文吃透 Spring 框架:原理、实践与面试全解析
后端
站大爷IP2 小时前
Python 的切片把我坑惨了,原来 `[:]` 是浅拷贝,而 `copy.deepcopy` 才是我的救命稻草
后端