利用有向网的邻接表存储结构实现Dijkstra算法的最短路径代码
时间: 2024-03-20 19:43:13 浏览: 90
好的,以下是利用邻接表存储结构实现Dijkstra算法的最短路径的代码:
```python
import sys
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[] for i in range(vertices)]
def add_edge(self, u, v, w):
self.graph[u].append((v, w))
def dijkstra(self, src):
dist = [sys.maxsize] * self.V
dist[src] = 0
visited = [False] * self.V
for i in range(self.V):
u = self.min_distance(dist, visited)
visited[u] = True
for v, w in self.graph[u]:
if not visited[v] and dist[u] != sys.maxsize and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
self.print_solution(dist)
def min_distance(self, dist, visited):
min_value = sys.maxsize
min_index = -1
for v in range(self.V):
if not visited[v] and dist[v] < min_value:
min_value = dist[v]
min_index = v
return min_index
def print_solution(self, dist):
print("Vertex Distance from Source")
for node in range(self.V):
print(node, " : ", dist[node])
g = Graph(9)
g.add_edge(0, 1, 4)
g.add_edge(0, 7, 8)
g.add_edge(1, 2, 8)
g.add_edge(1, 7, 11)
g.add_edge(2, 3, 7)
g.add_edge(2, 8, 2)
g.add_edge(2, 5, 4)
g.add_edge(3, 4, 9)
g.add_edge(3, 5, 14)
g.add_edge(4, 5, 10)
g.add_edge(5, 6, 2)
g.add_edge(6, 7, 1)
g.add_edge(6, 8, 6)
g.add_edge(7, 8, 7)
g.dijkstra(0)
```
这段代码实现了一个有向图的邻接表存储结构,并使用Dijkstra算法求出了从源点到其他各点的最短路径。其中,`Graph`类表示一个有向图,`add_edge`方法用于添加边,`dijkstra`方法是Dijkstra算法的实现,`min_distance`方法用于寻找未访问节点中距离源点最近的节点,`print_solution`方法用于输出结果。在这个例子中,我们使用了一个9个节点的图进行了测试。
阅读全文