将图上的顶点分为已访问visited
和未访问node
两个集合.
每次从visited
向外拓展一个点,拓展规则是在可更新的点里是距离最小的.
算法伪代码:
def dijkstra():
初始化 visited 和 node 集合,distance[]
visited 加入源节点
node 移除源节点
while node 非空:
最短路径长度 = inf
for each visited:
for each 相邻节点:
if 长度<最短路径长度:
更新最短路径长度
维护 distance
保存此节点
visited 加入更新节点
node 移除更新节点
return distance
具体实现:
'''
dijkstra algorithm demo
graph size:6*6
node index start from 0
'''
import numpy as np
graph_list = [[0, 2, 1, 4, 5, 1],
[1, 0, 4, 2, 3, 4],
[2, 1, 0, 1, 2, 4],
[3, 5, 2, 0, 3, 3],
[2, 4, 3, 4, 0, 1],
[3, 4, 7, 3, 1, 0]]
def dijkstra(graph, src):
# init
visited = []
distance = {src: 0}
node = list(range(len(graph[0])))
if src in node:
node.remove(src)
visited.append(src)
else:
return None
for i in node:
distance[i] = graph[src][i]
prefer = src
while node:
_distance = float('inf')
for i in visited:
for j in node:
if graph[i][j] > 0:
if _distance > distance[i] + graph[i][j]:
_distance = distance[j] = distance[i] + graph[i][j]
prefer = j
visited.append(prefer)
node.remove(prefer)
return distance
if __name__ == '__main__':
distance = dijkstra(graph_list, 0)
print(distance)