Graphs
Nievergelt & Hinrichs · Ch. 6 · Algorithms and Data Structures
A graph is vertices and edges. Represent it as an adjacency list (sparse) or adjacency matrix (dense). BFS explores level by level. DFS explores depth-first. Both run in O(V + E).
Adjacency list representation
Scheme
Breadth-first search
BFS uses a queue. It visits all vertices at distance d before any at distance d+1. This gives shortest paths in unweighted graphs.
Scheme
Depth-first search
DFS uses a stack (or recursion). It explores as deep as possible before backtracking. Useful for topological sort, cycle detection, and connected components.
Scheme