Dijkstra算法迷宫地图里多节点Python实现
时间: 2023-06-25 17:03:14 浏览: 93
Dijkstra算法python实现
以下是Dijkstra算法在迷宫地图里多节点的Python实现:
```python
import heapq
def dijkstra(maze, start, end):
# 初始化起点和终点
start_node = (start, 0)
end_node = (end, float('inf'))
# 初始化距离字典和visited集合
distances = {node: float('inf') for row in maze for node in row}
distances[start_node[0]] = start_node[1]
visited = set()
# 初始化堆并添加起点
heap = []
heapq.heappush(heap, start_node)
while heap:
# 弹出距离最小的节点
current_node = heapq.heappop(heap)[0]
if current_node == end_node[0]:
return distances[end_node[0]]
if current_node in visited:
continue
visited.add(current_node)
# 遍历四个方向
for i, j in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
row = current_node[0][0] + i
col = current_node[0][1] + j
if 0 <= row < len(maze) and 0 <= col < len(maze[0]) and maze[row][col] != 1:
neighbor = ((row, col), 1 if maze[row][col] == 2 else 0)
distance = distances[current_node] + neighbor[1]
if distance < distances[neighbor[0]]:
distances[neighbor[0]] = distance
heapq.heappush(heap, (neighbor, distance))
return -1
```
其中,`maze`是一个二维列表,表示迷宫地图。0表示可以通过的空地,1表示障碍物,2表示终点。`start`和`end`是起点和终点的坐标。函数返回起点到终点的最短距离。
阅读全文