Python单源最短路径问题代码
时间: 2024-03-28 19:33:37 浏览: 70
python实现最短路径的实例方法
Python中求解单源最短路径问题的常用算法是Dijkstra算法。下面是一个简单的Python代码示例:
```python
import sys
# 定义一个图类
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for _ in range(vertices)] for _ in range(vertices)]
# 找到距离最小的节点
def min_distance(self, dist, visited):
min_dist = sys.maxsize
min_index = -1
for v in range(self.V):
if dist[v] < min_dist and not visited[v]:
min_dist = dist[v]
min_index = v
return min_index
# 打印最短路径
def print_solution(self, dist):
print("节点\t距离")
for node in range(self.V):
print(node, "\t\t", dist[node])
# 使用Dijkstra算法求解单源最短路径
def dijkstra(self, src):
dist = [sys.maxsize] * self.V # 存储最短距离
dist[src] = 0 # 源节点到自身的距离为0
visited = [False] * self.V # 记录节点是否已被访问
for _ in range(self.V):
u = self.min_distance(dist, visited)
visited[u] = True
for v in range(self.V):
if (
self.graph[u][v] > 0
and not visited[v]
and dist[v] > dist[u] + self.graph[u][v]
):
dist[v] = dist[u] + self.graph[u][v]
self.print_solution(dist)
# 示例代码
g = Graph(9)
g.graph = [
[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0],
]
g.dijkstra(0)
```
这段代码实现了一个Graph类,其中包含了Dijkstra算法的实现。首先定义了一个图的大小,然后通过二维数组`graph`表示图的邻接矩阵。在`dijkstra`方法中,通过遍历节点来计算源节点到其他节点的最短距离,并将结果存储在`dist`数组中。最后通过`print_solution`方法打印出最短路径的结果。
阅读全文