Graph algorithms study guide: BFS, DFS, Dijkstra, Prim, Kruskal
How I organized the graph unit in my head. My own summary, not official material.
Traversals
- BFS: queue plus visited set. Visits in order of distance (edge count).
- DFS: stack or recursion plus visited set. Goes deep before wide.
Shortest paths
- Dijkstra: priority queue by distance, non-negative weights.
Minimum spanning trees (connect everything as cheaply as possible)
- Prim: grow one tree outward, always taking the cheapest edge leaving it.
- Kruskal: sort all edges, add each one unless it would create a cycle (use disjoint sets to check).
Practice idea: draw one small weighted graph and run all five algorithms on it. Comparing the visit orders taught me more than any single problem did.
Comments
Kruskal plus disjoint sets was the hardest part for me. Nice summary.
Running all five on the same graph is a great idea. Doing that this weekend.