标签:len 最短 bfs step grid dfs 点集 934
题目描述
矩阵中有两个岛屿
问岛之间的最小距离?
基本分析
- 怎么求第一个岛的所有点?找到第一个1后bfs
- 怎么保证不重复添加?入队的点设置为-1
- 怎么求到第二个岛的最小距离?第一个岛的所有点入队,遍历一轮step+1,遇到1的时候返回step
代码
class Solution:
def shortestBridge(self, grid):
m, n = len(grid), len(grid[0])
flag = True
for i, row in enumerate(grid):
for j, v in enumerate(row):
if v != 1:
continue
q = deque([(i, j)])
grid[i][j] = -1
island1 = []
while q:
x, y = q.popleft()
island1.append((x, y))
for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
if 0 <= nx < m and 0 <= ny <n and grid[nx][ny] == 1:
q.append((nx, ny))
grid[nx][ny] = -1
step = 0
q = deque(island1)
while q:
for _ in range(len(q)):
x, y = q.popleft()
for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
if 0 <= nx < m and 0 <= ny < n:
if grid[nx][ny] == 1:
return step
if grid[nx][ny] == 0:
q.append((nx, ny))
grid[nx][ny] = -1
step += 1
总结
- 为啥在循环内bfs?找到第一个点集就开始bfs,不是在循环外bfs。如果这样,点集会是第二个岛,其余点都是-1了,没打进行第二轮bfs
- step怎么算?初始值设置为0,传播一圈后+1
基本分析
- 找第一个点集还有啥其他方法?dfs
代码
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def dfs(x, y):
grid[x][y] = -1
q.append((x, y))
for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 1:
dfs(nx, ny)
for i, row in enumerate(grid):
for j, v in enumerate(row):
if v != 1:
continue
q = []
dfs(i, j)
step = 0
q = deque(q)
while q:
for _ in range(len(q)):
x, y = q.popleft()
for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
if 0 <= nx < m and 0 <= ny < n:
if grid[nx][ny] == 0:
q.append((nx, ny))
grid[nx][ny] = -1
if grid[nx][ny] == 1:
return step
step += 1
总结
- 掌握dfs存第一个点集的思路
待完善
基本分析
- xxx
代码
总结
- xxx
标签:len,
最短,
bfs,
step,
grid,
dfs,
点集,
934
From: https://www.cnblogs.com/zk-icewall/p/17315785.html