class Solution:
# 【DFS+BFS】连通分量搜索+多源最短路径
def shortestBridge(self, A: List[List[int]]) -> int:
source = collections.deque()
m = len(A)
n = len(A[0])
def dfs(i, j):
if i < 0 or j < 0 or i >= m or j >= n or A[i][j] == 0: return
A[i][j] = 0 # 遍历过的设置为0
source.append((i, j)) # 遍历过的加入source
# 从4个方向继续深度遍历
for (r, c) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
dfs(r, c)
find = False
for i in range(m):
for j in range(n):
if A[i][j] == 1 and not find:
dfs(i,j)
find = True # 寻找到了第一个岛,则停止dfs
seen = set(source)
level = 0
while source:
# 遍历source的每一个坐标点
for _ in range(len(source)):
i,j = source.popleft()
for r, c in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
# 若越界 或 已经遍历过,则跳过
if r < 0 or c < 0 or r >= m or c >= n or (r,c) in seen: continue
# 若当前位置为0,则加入
if A[r][c] == 0:
source.append((r,c))
seen.add((r,c))
# 若当前位置为1,则已经可以联通
else:
return level
# 每遍历完一遍source都未能联通,则至少需要翻转一个点,则加一
level += 1
return level
934. 最短的桥(Medium)
最新推荐文章于 2022-10-25 10:03:44 发布