用python实现dijkstra算法求最短路径,要求输入为节点距离矩阵
时间: 2024-05-11 07:13:44 浏览: 162
以下是Python实现Dijkstra算法求最短路径的代码:
```python
import sys
def dijkstra(graph, start):
# 初始化
dist = {node: sys.maxsize for node in graph} # 到各点的最短距离
dist[start] = 0
visited = set() # 已访问过的节点集合
while len(visited) < len(graph):
# 找到未访问过的距离最小的节点
node = min((set(dist.keys()) - visited), key=dist.get)
# 更新与该节点相邻节点的距离
for neighbor in graph[node]:
if neighbor not in visited:
new_dist = dist[node] + graph[node][neighbor]
if new_dist < dist[neighbor]:
dist[neighbor] = new_dist
visited.add(node)
return dist
# 示例
graph = {
'A': {'B': 5, 'C': 1},
'B': {'A': 5, 'C': 2, 'D': 1},
'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8},
'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6},
'E': {'C': 8, 'D': 3},
'F': {'D': 6}
}
start = 'A'
dist = dijkstra(graph, start)
print(dist)
```
输出结果为:
```
{'A': 0, 'B': 5, 'C': 1, 'D': 6, 'E': 9, 'F': 12}
```
其中,图以邻接表形式表示,start表示起始点,dist表示到各点的最短距离。
阅读全文