该算法适用于单源最短路径,即从一个点出发,到达其他点最近的路线和距离。
数据结构:
- 两个数组——unvisited_nodes, visited_node
- 一开始,unvisited_nodes 数组里存放所有 node class——(index of node, least weight, parent node)
least weight: 起始点到该点的最小权
parent node:该点的最小权是由parent node 的最小权 加上两点之间的weight 得到的。
过程:
- 初始化:起始点A 的weight为0,其他点为无穷。
- 根据边的权限,refresh A点的邻接点的weight(在unvisited_nodes数组的class里)。每刷新一次就对该数组heapify(min)一次。
- 从unvisited_nodes 数组里pop出第一个node——B,放入visited_node 数组。
- 根据边的权限,如果 min_weight of B + weight of edge < min_weight of B的邻接点, refresh 该邻接点的least weight和parent node(在unvisited_nodes数组的class里)。每刷新一次就对该数组heapify(min)一次。
重复3,4。 直到unvisited_nodes数组为空。
最后再visted_node 数组里,我们得到一个装有所有node的(index of node, least weight, parent node)的数组,That is。
与bellman-ford对比
- When the weight associated with an edge is negative, the Dijkstra Algorithm is useless. Only Bellman-ford is used here.
- Dijkstra Algorithm is based on nodes, all the relaxations are processing on the path.
Bellman-ford is based on edges, the all relaxations are processing edge by edge. - the basic concept of Dijkstra Algorithm is the Greedy search. In contract, the basic concept of bellman-ford is the Dynamic programming.