迷宫中有八个节点,从起点依次到这八个节点再到终点的最短路径Dijkstra算法用Python实现
时间: 2023-06-20 22:07:29 浏览: 128
好的,下面是用 Python 实现 Dijkstra 算法求解迷宫中八个节点的最短路径的代码:
```python
import heapq
def dijkstra(start, end, graph):
# 初始化起点的距离为0,其他节点的距离为无穷大
dist = {node: float('inf') for node in graph}
dist[start] = 0
# 使用堆来存储所有的未访问节点和它们的距离
heap = []
heapq.heappush(heap, (0, start))
while heap:
(curr_dist, curr_node) = heapq.heappop(heap)
# 如果当前节点已经被访问过了,则跳过
if curr_dist > dist[curr_node]:
continue
# 遍历当前节点的邻居,并更新它们的距离
for neighbor, weight in graph[curr_node].items():
distance = curr_dist + weight
if distance < dist[neighbor]:
dist[neighbor] = distance
heapq.heappush(heap, (distance, neighbor))
# 返回起点到终点的最短距离
return dist[end]
# 定义迷宫的节点
nodes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'End']
# 定义迷宫的邻接矩阵
graph = {
'A': {'B': 2, 'C': 1},
'B': {'A': 2, 'D': 2},
'C': {'A': 1, 'F': 4},
'D': {'B': 2, 'E': 3},
'E': {'D': 3, 'G': 1},
'F': {'C': 4, 'H': 3},
'G': {'E': 1, 'H': 2},
'H': {'F': 3, 'G': 2, 'End': 1},
'End': {'H': 1},
}
# 计算起点到终点的最短距离
start = 'A'
end = 'End'
shortest_distance = dijkstra(start, end, graph)
# 输出结果
print(f"The shortest distance from {start} to {end} is {shortest_distance}.")
```
在上面的代码中,我们定义了一个 `dijkstra` 函数,它接受起点、终点和邻接矩阵作为输入,并返回起点到终点的最短距离。该函数的实现过程与 Dijkstra 算法的伪代码非常相似。
然后,我们定义了迷宫的节点和邻接矩阵,并将它们作为参数传递给 `dijkstra` 函数。最后,我们输出起点到终点的最短距离。
希望这个例子能对你有所帮助!
阅读全文