python中dijkstra算法代码
时间: 2023-11-12 07:55:48 浏览: 95
以下是Python中实现Dijkstra算法的代码:
```python
import sys
def dijkstra(graph, source):
distance = {node: sys.maxsize for node in graph}
distance[source] = 0
visited = set()
while len(visited) < len(graph):
node = min((dist, node) for node, dist in distance.items() if node not in visited)[1]
visited.add(node)
for neighbor, weight in graph[node].items():
new_distance = distance[node] + weight
if new_distance < distance[neighbor]:
distance[neighbor] = new_distance
return distance
# 示例图的邻接矩阵表示
graph = {
'A': {'B': 3, 'C': 4, 'D': 7},
'B': {'C': 1, 'F': 5},
'C': {'F': 6, 'D': 2},
'D': {'E': 3, 'G': 6},
'E': {'G': 3, 'H': 4},
'F': {'E': 1, 'H': 8},
'G': {'H': 2},
'H': {'G': 2}
}
source = 'A'
distances = dijkstra(graph, source)
print(distances)
```
阅读全文