用python实现dijkstra算法
时间: 2023-10-20 19:20:42 浏览: 109
好的,以下是用Python实现Dijkstra算法的代码:
```python
import heapq
def dijkstra(graph, start, end):
# 初始化
heap = [(0, start)]
visited = set()
paths = {start: []}
# 探索
while heap:
(cost, node) = heapq.heappop(heap)
# 如果已经探索过,直接跳过
if node in visited:
continue
# 记录探索过的节点
visited.add(node)
# 如果已经找到终点,直接跳出循环
if node == end:
break
# 搜寻与当前节点相邻的节点,并计算花费
for next_node in graph[node]:
cost_next = cost + graph[node][next_node]
if next_node not in paths or cost_next < paths[next_node][0]:
paths[next_node] = (cost_next, node)
heapq.heappush(heap, (cost_next, next_node))
# 组织路径
path = [end]
while path[-1] != start:
path.append(paths[path[-1]][1])
return path[::-1]
# 示例
graph = {
'A': {'B': 3, 'D': 2},
'B': {'A': 3, 'C': 4, 'D': 6},
'C': {'B': 4, 'F': 5},
'D': {'A': 2, 'B': 6, 'E': 1},
'E': {'D': 1, 'F': 2},
'F': {'C': 5, 'E': 2}
}
start, end = 'A', 'F'
print(dijkstra(graph, start, end))
```
希望我的代码和解释能够帮到你,如果有其它问题,可以继续提出。
阅读全文