Graph Representation, BFS and DFS
Represent graphs with adjacency lists and matrices, and explore them with BFS and DFS to find components, cycles and unweighted shortest paths.
Intermediate · about 8 hours · difficulty 3/5
Learn first: Queues and Deques, Recursion and Divide and Conquer
A graph is a set of vertices connected by edges, which can be directed or undirected and weighted or unweighted. Many problems are graphs in disguise: grids, dependency lists, social networks, word ladders and state machines.
Representation
- Adjacency list (vector of vectors, list of lists): O(V + E) memory, the default choice.
- Adjacency matrix: O(V^2) memory, O(1) edge lookup, fine for small dense graphs.
- Implicit graphs: a grid where each cell connects to its 4 neighbours; generate neighbours on the fly with direction arrays.
BFS
Uses a queue and visits nodes in order of distance from the source. In an unweighted graph the first time you reach a node is via a shortest path. Multi-source BFS starts with several sources in the queue (Rotting Oranges, distance to nearest 0).
DFS
Uses recursion or a stack to go deep first. Useful for connected components, flood fill, cycle detection, path existence and as the base of topological sort and bridge finding.
Cycle detection
- Undirected: a visited neighbour that is not your parent means a cycle.
- Directed: track nodes on the current recursion path (three colours: unvisited, in progress, done). An edge to an in-progress node is a back edge, meaning a cycle.
Pitfalls
Marking visited when popping instead of when pushing in BFS (causes duplicates in the queue), forgetting disconnected components, and recursion depth on large grids. Both BFS and DFS run in O(V + E).
Key concepts
- Adjacency list vs matrix
- Grids as implicit graphs
- Breadth-first search
- Depth-first search
- Connected components and flood fill
- Multi-source BFS
- Cycle detection (directed and undirected)
- Bipartite check
- 0-1 BFS with a deque
Mini project
Solve 10 problems: Number of Islands, Flood Fill, Max Area of Island, Rotting Oranges, 01 Matrix, Clone Graph, Pacific Atlantic Water Flow, Surrounded Regions, Is Graph Bipartite, and Word Ladder.
Check yourself
Why does BFS give shortest paths in an unweighted graph but not in a weighted one?
Free resources
- VisuAlgo: Graph Traversal (VisuAlgo)
- Breadth-first search (cp-algorithms)
- Competitive Programmer's Handbook (Ch. 11-12) (CSES)