迪杰斯特拉算法path[]
时间: 2024-01-27 16:04:46 浏览: 154
迪杰斯特拉算法中的path[]是用来存储从起点到每个顶点的最短路径的列表。在算法的执行过程中,通过不断更新path[]列表,可以得到从起点到终点的最短路径。
以下是一个使用迪杰斯特拉算法求解最短路径的示例代码:
```python
def Dijkstra(network, s, d):
print("Start Dijkstra Path......")
path = [] # s-d的最短路径
n = len(network) # 邻接矩阵维度,即节点个数
fmax = 999
w = [[0 for i in range(n)] for j in range(n)] # 邻接矩阵
for i in range(n):
for j in range(n):
if network[i][j] == 0:
w[i][j] = fmax
else:
w[i][j] = network[i][j]
dist = [fmax] * n # 存储起点到每个顶点的最短距离
visited = [False] * n # 记录顶点是否已被访问
prev = [-1] * n # 记录最短路径中每个顶点的前驱顶点
dist[s] = 0 # 起点到自身的距离为0
for i in range(n):
min_dist = fmax
u = -1
for j in range(n):
if not visited[j] and dist[j] < min_dist:
min_dist = dist[j]
u = j
if u == -1:
break
visited[u] = True
for v in range(n):
if not visited[v] and dist[u] + w[u][v] < dist[v]:
dist[v] = dist[u] + w[u][v]
prev[v] = u
# 构建最短路径
path.append(d)
while prev[d] != -1:
d = prev[d]
path.append(d)
path.reverse()
return path
network = [[0, 2, 4, 0, 0, 0],
[2, 0, 1, 4, 2, 0],
[4, 1, 0, 0, 3, 0],
[0, 4, 0, 0, 3, 2],
[0, 2, 3, 3, 0, 2],
[0, 0, 0, 2, 2, 0]]
start = 0 # 起点
end = 5 # 终点
shortest_path = Dijkstra(network, start, end)
print("Shortest path from", start, "to", end, ":", shortest_path)
```
这段代码使用邻接矩阵表示图的连接关系,通过迪杰斯特拉算法计算从起点到终点的最短路径,并将最短路径存储在path[]列表中。最后,打印出从起点到终点的最短路径。
阅读全文