Leetcode 827.最大人工岛(Making A Large Island)

Leetcode 827.最大人工岛

1 题目描述(Leetcode题目链接

  在二维地图上, 0代表海洋, 1代表陆地,我们最多只能将一格 0 海洋变成 1变成陆地。

进行填海之后,地图上最大的岛屿面积是多少?(上、下、左、右四个方向相连的 1 可形成岛屿)

输入: [[1, 0], [0, 1]]
输出: 3
解释: 将一格0变成1,最终连通两个小岛得到面积为 3 的岛屿。
输入: [[1, 1], [1, 0]]
输出: 4
解释: 将一格0变成1,岛屿的面积扩大为 4

说明:

  • 1 <= grid.length = grid[0].length <= 50
  • 0 <= grid[i][j] <= 1

2 题解

  先深度优先搜索记录每个岛屿的面积,然后给每个岛屿标号。再遍历0的位置,将这个0连着的岛屿面积加一起求最大值。

class Solution:
    def largestIsland(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        land = collections.defaultdict(int)
        res = 0
        def dfs(i, j, color):
            if grid[i][j] != 1:
                return 0
            res = 1
            grid[i][j] = color
            for d in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                x, y = i + d[0], j + d[1]
                if 0 <= x < m and 0 <= y < n:
                    res += dfs(x, y, color)
            return res
        
        color = 2
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    land[color] = dfs(i, j, color)
                    res = max(res, land[color])
                    color += 1

        for i in range(m):
            for j in range(n):
                if grid[i][j] == 0:
                    seen = set()
                    S = 1
                    for d in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                        x, y = i + d[0], j + d[1]
                        if 0 <= x < m and 0 <= y < n and grid[x][y] not in seen:
                            S += land[grid[x][y]]
                            seen.add(grid[x][y])
                    res = max(S, res)
                            
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值