Summary of All Shortest Path Algorithms
Shortest Path (SP) Algorithms | BFS | A* | Dijkstra’s | Bellman Ford | Floyd Warshall |
---|---|---|---|---|---|
Complexity | |||||
Recommended graph size | Large | Large | Large/Medium | Medium/Small | Small |
All-Pairs | Only works on unweighted graphs | No | Ok | Bad | Yes |
Can detect negative cycles? | - | - | - | ✓ | ✓ |
SP on graph with unweighted edges | ✓(Best) | ✓ | ✓ | ✓(Bad) | ✓(Bad) |
SP on graph with weighted edges | Must expand graph | ✓(Best) | ✓ | ✓ | ✓(Bad) |
Single Source Shortest Path (SSSP)
alg. BFS Shortest Path
- Assumption: Graph doesn’t have weights
- Idea: BFS, but every time you encounter a tense edge, relax it
alg. Dijkstra’s Shortest Path
- Assumption. graph has non-negative edge weights
- Idea. BFS Shortest Path, but you choose the next vertex by how likely they are to be the shortest path (=maintain a Priority Queue based on path length)
- Complexity
- Time:
alg. A-Star (A*) Shortest Path
- Assumption. graph has non-negative edge weights
- Idea. Dijkstra using Priority Queue, but the priority is calculated on a heuristic
- Complexity.
- Time: using binary heap
alg. Bellman–Ford Shortest Path
- Idea:
- Repeat BFS edge relaxation for times. Get shortest path
- Repeat BFS edge relaxation again, for times. But this time, if any cost values are updated, the node is part of a negative cycle. Mark cost to that node as .
- See Bellman Ford Algorithm | Graph Theory - YouTube
- Able to deal with negative edges/negative cycles
- Often used in finance for identifying No-Arbitrage opportunities.
- Complexity. Time:
All Pairs Shortest Path (APSP)
alg. Floyd-Warshall Shortest Path
- Idea: Dynamically Programmed algorithm. from to , compare the two paths:
- using only vertices
- , but only using vertices
- Take the smaller of the two.
- Example:
- DP Table: is the shortest path from using nodes
- See also: Floyd–Warshall algorithm - Wikiwand
- Complexity. Time: , Space by retaining most recent only
Tips and Tricks
- If the problem demands you multiply edge weights instead of summing them, use of weights instead to transform it back into a problem with summation of edge weights. (See Example)