talk is cheap ,show me code
from collections import deque
def bidirectional_bfs(grid, start, end):
if start == end:
return 0
# 初始化两个队列和访问集合
start_queue = deque([start])
end_queue = deque([end])
visited_from_start = {start}
visited_from_end = {end}
# 记录步数
steps = 0
while start_queue and end_queue:
# 每次从两个方向中选择节点数较少的队列进行扩展
if len(start_queue) > len(end_queue):
start_queue, end_queue = end_queue, start_queue
visited_from_start, visited_from_end = visited_from_end, visited_from_start
# 扩展一层
steps += 1
for _ in range(len(start_queue)):
node = start_queue.popleft()
# 获取当前节点的所有相邻节点
for neighbor in get_neighbors(grid, node):
if neighbor in visited_from_end:
return steps
if neighbor not in visited_from_start:
visited_from_start.add(neighbor)
start_queue.append(neighbor)
return -1 # 如果无法到达终点
def get_neighbors(grid, node):
# 返回节点上下左右四个方向的邻居节点
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
neighbors = []
x, y = node
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == 0:
neighbors.append((nx, ny))
return neighbors