該算法適用于單源最短路徑,即從一個點出發(fā),到達(dá)其他點最近的路線和距離。
數(shù)據(jù)結(jié)構(gòu):
- 兩個數(shù)組——unvisited_nodes, visited_node
- 一開始,unvisited_nodes 數(shù)組里存放所有 node class——(index of node, least weight, parent node)
least weight: 起始點到該點的最小權(quán)
parent node:該點的最小權(quán)是由parent node 的最小權(quán) 加上兩點之間的weight 得到的。
過程:
- 初始化:起始點A 的weight為0,其他點為無窮。
- 根據(jù)邊的權(quán)限,refresh A點的鄰接點的weight(在unvisited_nodes數(shù)組的class里)。每刷新一次就對該數(shù)組heapify(min)一次。
- 從unvisited_nodes 數(shù)組里pop出第一個node——B,放入visited_node 數(shù)組。
- 根據(jù)邊的權(quán)限,如果 min_weight of B + weight of edge < min_weight of B的鄰接點, refresh 該鄰接點的least weight和parent node(在unvisited_nodes數(shù)組的class里)。每刷新一次就對該數(shù)組heapify(min)一次。
重復(fù)3,4。 直到unvisited_nodes數(shù)組為空。
最后再visted_node 數(shù)組里,我們得到一個裝有所有node的(index of node, least weight, parent node)的數(shù)組,That is。
第一個點
更新鄰接點
pop 出最小值的node加入visited_node,刷新鄰接點
pop 出最小值的node加入visited_node,刷新鄰接點
pop 出最小值的node加入visited_node,刷新鄰接點
與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.