mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #2318 from shaochenren/master
Problem 0827 最大人工岛屿,添加python2解法
This commit is contained in:
@ -282,6 +282,68 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```Python
|
||||
class Solution(object):
|
||||
# 可能的移动方向
|
||||
DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
|
||||
|
||||
def exploreIsland(self, row, col, grid, visited, island_id):
|
||||
"""
|
||||
从给定的单元格开始,使用深度优先搜索探索岛屿。
|
||||
"""
|
||||
if (row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or
|
||||
visited[row][col] or grid[row][col] == 0):
|
||||
return 0
|
||||
|
||||
visited[row][col] = True
|
||||
grid[row][col] = island_id
|
||||
island_size = 1
|
||||
for dr, dc in self.DIRECTIONS:
|
||||
island_size += self.exploreIsland(row + dr, col + dc, grid, visited, island_id)
|
||||
return island_size
|
||||
|
||||
def largestIsland(self, grid):
|
||||
"""
|
||||
通过最多将一个0更改为1,找到可以形成的最大岛屿的大小。
|
||||
"""
|
||||
rows, cols = len(grid), len(grid[0])
|
||||
island_sizes = {}
|
||||
island_id = 2 # 从2开始标记岛屿(因为0代表水,1代表未被发现的陆地)
|
||||
is_all_land = True
|
||||
visited = [[False] * cols for _ in range(rows)]
|
||||
|
||||
# 标记每个岛屿并存储其大小
|
||||
for r in range(rows):
|
||||
for c in range(cols):
|
||||
if grid[r][c] == 0:
|
||||
is_all_land = False
|
||||
elif not visited[r][c] and grid[r][c] == 1:
|
||||
island_size = self.exploreIsland(r, c, grid, visited, island_id)
|
||||
island_sizes[island_id] = island_size
|
||||
island_id += 1
|
||||
|
||||
# 如果整个网格是陆地,则返回其大小
|
||||
if is_all_land:
|
||||
return rows * cols
|
||||
|
||||
# 计算可以通过将一个0更改为1来形成的最大岛屿
|
||||
max_island_size = 0
|
||||
for r in range(rows):
|
||||
for c in range(cols):
|
||||
if grid[r][c] == 0:
|
||||
adjacent_islands = set()
|
||||
for dr, dc in self.DIRECTIONS:
|
||||
nr, nc = r + dr, c + dc
|
||||
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] > 1:
|
||||
adjacent_islands.add(grid[nr][nc])
|
||||
new_island_size = sum(island_sizes[island] for island in adjacent_islands) + 1
|
||||
max_island_size = max(max_island_size, new_island_size)
|
||||
|
||||
return max_island_size
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user