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