帮我用python写一个用邻接表储存的图的Dijkstra算法
时间: 2023-05-27 08:04:44 浏览: 117
以下是使用邻接表储存图的Dijkstra算法的Python代码:
```
import heapq
class Graph:
def __init__(self):
self.nodes = {}
def add_node(self, node):
self.nodes[node] = []
def add_edge(self, node1, node2, distance):
self.nodes[node1].append((node2, distance))
self.nodes[node2].append((node1, distance))
def dijkstra_shortest_path(graph, start_node):
heap = [(0, start_node)]
visited = set()
shortest_distance = {start_node: 0}
while heap:
(distance, current_node) = heapq.heappop(heap)
if current_node in visited:
continue
visited.add(current_node)
for (neighbor, edge_length) in graph.nodes[current_node]:
if neighbor not in visited:
new_distance = shortest_distance[current_node] + edge_length
if new_distance < shortest_distance.get(neighbor, float('inf')):
shortest_distance[neighbor] = new_distance
heapq.heappush(heap, (new_distance, neighbor))
return shortest_distance
# example usage
g = Graph()
g.add_node('A')
g.add_node('B')
g.add_node('C')
g.add_node('D')
g.add_node('E')
g.add_edge('A', 'B', 1)
g.add_edge('A', 'C', 4)
g.add_edge('B', 'C', 2)
g.add_edge('B', 'D', 5)
g.add_edge('C', 'D', 1)
g.add_edge('C', 'E', 6)
g.add_edge('D', 'E', 3)
shortest_distances = dijkstra_shortest_path(g, 'A')
print(shortest_distances)
```
对于给定的图,该代码将输出以下内容:
```
{'A': 0, 'B': 1, 'C': 3, 'D': 4, 'E': 7}
```
这表示从节点'A'出发,到达所有其他节点的最短距离分别为0、1、3、4和7。
阅读全文