今天来总结一下常用的最短路径算法。符号简称:E -- # of edges; V -- # of vertexes
Single Source Shortest Path:
on non-weighted Graph: Bredth First Search
Non-Negative-Cylic Graph: Dikstra -- BFS + Priority Queue -- O(E) + O(V log V)
Graph With Negative Cycle: Bellman Ford's: Relax Node for N-1 times, then check if can still relax node (negative cycle)
Time Complexity: O(E * V)
还有国产的Shortest Path Faster Algorithm: 用一个队列记录当前relex的node。每次拿出要relex的node来继续relex。如果有一个node relex的次数超过了n次,那么说明有负环 —— O(kE),一般情况下k < 2。国产的东西就是好。
Minimum Spaning Tree:
Prim's -- O(E log V): 找当前点可见边中,连接没有visit过的点的最短的。
Kruskal's -- O(E log(E)) = O(E log(V)):首先Sort一下所有边。然后从weight最小的两条边一点点加点进来,直到包含了所有点。
All Pair Shortest Path:
Floyd Warshall (V^3): 只要记住这个recursive formula就会写code了:
define function: shortest(i,j,k) ==> the shortest path from node i to node j, only pass by element from set {1,...,k}
shortestPath(i,j,0) = w(i,j)
shortestPath(i,j,k) = min(shortestPath(i,j,k-1), shortestPath(i,k,k-1) + shortestPath(k,j,k-1))