Dijkstra算法–最短路径问题
(11.28 今天重新回来看了一下,当时留了个坑,没考虑两点不可达)(待纠正)
参考文献:
求解步骤
- 集合V表示所有的点。定义两个集合S、U,S表示已经标记的点,初始状态只有起点,U表示未标记的点以及未标记点到起点的最短距离
- 从U中选出“距离起点最短的顶点k”,并将顶点k加入S中,同时将k从U中移除
- 以S为参照,更新U中未标记点到起点的最短距离。S中新加入的顶点k,给未标记点到起点提供的新的可能更短的路径
- 重复步骤2、3,直到集合S等于集合V(即遍历完所有顶点)
python
- 用Graph表示两点之间的距离
- 将顶点加入S,同时从U中删除
- 更新U中顶点到起点的最短距离
- 从U中选择距离起点最近的顶点加入S中,并从U中删除,重复第三步,直到所有点都在S中
import math
import numpy as np
def dijkstra(graph, ori):
# 定义返回结果
re = {ori: 0}
# 初始化,未求出最短路径的点
notFound = {}
for i in range(len(graph)):
notFound[i] = graph[ori][i]
notFound.pop(ori)
# 开始Dijkstra算法
for i in range(1,len(graph)):
# 1. 从[未求出最短路径的点]notFound中取出 最短路径的点
# 1.1 找到最短路径的点
min = math.inf
minIndex = 0
for j in notFound.keys():
if 0 < notFound[j] < min:
min = notFound[j]
minIndex = j
# 1.2 将最短距离的点 取出来 加入结果中,并将顶点从U中删除
re[minIndex] = min
notFound.pop(minIndex)
# 刷新 [未求出最短距离的点] notFound[] 中的最短距离
# 遍历刚刚找到最短距离的点,在此基础上计算该点到所有未标记的点的距离 + 该点的最短距离 与 起点的最短距离进行比较
for j in notFound.keys():
if graph[minIndex][j] > 0:
newDis = graph[minIndex][j] + re[minIndex]
if newDis < notFound[j] or notFound[j] == -1:
notFound[j] = newDis
return re
if __name__ == '__main__':
# -1表示该点不能到下一点
# graph = [
# [0, 2, -1, 6],
# [2, 0, 3, 2],
# [-1, 3, 0, 2],
# [6, 2, 2, 0]
# ]
graph = [
[-1, 10, -1, -1, -1, 3],
[-1, -1, 7, 5, -1, -1],
[-1, -1, -1, -1, -1, -1],
[3, -1, 4, -1, 7, -1],
[-1, -1, -1, -1, -1, -1],
[-1, 2, -1, 6, 1, -1]
]
print(graph)
result = dijkstra(graph, 0)
print(result)
仅供学习记录,侵删。