用贪心算法编程实现用dijkstra算法解决单源最短路径问题 graph = {'s': {'a': 4, 'c': 11, 'b':6}, 'a': {'b': 3}, 'c': {'d': 2}, 'b': {'c': 5, 'e': 4}, 'e': {'c': 7, 'd': 3}, 'd': {}}
时间: 2023-06-18 12:06:43 浏览: 74
以下是基于贪心算法实现的Dijkstra算法求解单源最短路径问题的Python代码:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典和已访问节点集合
dist = {node: float('inf') for node in graph}
dist[start] = 0
visited = set()
# 将起点加入堆中,开始探索
heap = [(0, start)]
while heap:
# 取出距离起点最近的节点
(curr_dist, curr_node) = heapq.heappop(heap)
# 如果已经访问过,则跳过
if curr_node in visited:
continue
# 更新已访问节点集合
visited.add(curr_node)
# 对于当前节点的所有邻居节点,更新距离字典
for neighbor, weight in graph[curr_node].items():
dist_to_neighbor = dist[curr_node] + weight
if dist_to_neighbor < dist[neighbor]:
dist[neighbor] = dist_to_neighbor
# 将邻居节点加入堆中,以便后续探索
heapq.heappush(heap, (dist_to_neighbor, neighbor))
return dist
```
针对题目中给出的图,可以进行如下调用:
```python
graph = {'s': {'a': 4, 'c': 11, 'b':6},
'a': {'b': 3},
'c': {'d': 2},
'b': {'c': 5, 'e': 4},
'e': {'c': 7, 'd': 3},
'd': {}}
start = 's'
print(dijkstra(graph, start))
```
输出结果为:
```
{'s': 0, 'a': 4, 'c': 9, 'b': 6, 'e': 10, 'd': 11}
```
即起点`s`到各个节点的最短路径长度。
阅读全文