Graph
Traverse
Algorithm | Time Complexity | Space Complexity | Notes |
---|---|---|---|
DFS | Use stack for iteration | ||
BFS | Use queue for iteration |
Shortest Path
- Dijkstra: Weighted BFS + Priority Queue iteration
- Sparse graph, use Adjacency List:
- Dense graph, use Adjacency Matrix:
- Bellman-Ford: Based on Dijkstra, but checks all edges for each iteration
- Floyd-Warshall: Bottom-up DP to calculate shortest distances between all pairs
Algorithm | Time Complexity | Space Complexity | Pros | Cons |
---|---|---|---|---|
Dijkstra | See above | Intuitive | No negative cycle detection | |
Bellman-Ford | Robust | Slow | ||
Floyd-Warshall | Fast | Need additional steps to construct path |
info
Bellman-Ford and Floyd-Warshall can handle negative weights and detect negative cycles, while Dijkstra can not.
Minimum Spanning Tree
- Borůvka's: Greedy algorithm, select the cheapest edge for each component
- Prim: Greedy algorithm, select the cheapest edge that connects exactly one old vertex and one new vertex
- Sparse graph, use Adjacency List
- with binary heap:
- with Fibonacci heap:
- Dense graph, use Adjacency Matrix:
- Sparse graph, use Adjacency List
- Kruskal: Greedy algorithm, select the cheapest edge that connects at least one new vertex
Algorithm | Time Complexity |
---|---|
Borůvka's | |
Prim | See above |
Kruskal |
tip
See optimization for special cases on Wikipedia