# start = 0, visited = []: 存入最短路径中已有的点,初始化一个起点,
# unvisited=[]:存入尚未存入最短路径的点, 初始化为除了起点的所有点, 只要len(unvisited)>0,就要继续寻找
# distance: 存入距离,最短路径距离,初始化为起点到所有点的距离,graph[start], idx代表最短路径上的点的index
def startwith(start, graph):
visited = [start]
unvisited = [x for x in range(len(graph)) if x!=start]
distance=graph[start]
while len(unvisited):
idx = unvisited[0]
for i in unvisited:
if distance[i]<distance[idx]:
idx = i
# 当找到unvisited中最小的路径的点后,将最小的点移除出unvisited. 并添加到visited中。
unvisited.remove(idx)
visited.append(idx)
for i in unvisited:
if distance[idx]+graph[idx][i]<distance[i]:
distance[i]=distance[idx]+graph[idx][i]
return distance
if __name__ == "__main__":
inf = 9999
graph = [[0, 1, 12, inf, inf, inf],
[inf, 0, 9, 3, inf, inf],
[inf, inf, 0, inf, 5, inf],
[inf, inf, 4, 0, 13, 15],
[inf, inf, inf, inf, 0, 4],
[inf, inf, inf, inf, inf, 0]]
# dist = startwith(start=0, graph=graph)
dist1 = startwith(start=0, graph=graph)
print(dist1)
Dijkstra
于 2023-05-01 13:28:40 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)