synopsis · Trees & graphs · chapter 26
Graphs: BFS & DFS
10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A graph = vertices + edges. Store it as an adjacency list
List<List<Integer>>: O(V + E) memory. Grids and puzzles are graphs too. - use it when
Fewest steps with equal-cost moves → BFS. Count or mark everything connected → DFS or BFS. Many sources spreading at once → multi-source BFS.
- template
BFS:
offer(s); seen[s] = true;while the queue isn't empty:u = poll(); for each neighbour v not seen → mark it,offer(v). - cost
BFS and DFS: O(V + E) time, O(V) extra space. A grid is O(rows × cols). Bipartite and cycle checks cost the same.
- trap
Mark visited when you enqueue, not when you poll — or the same vertex is queued many times.
- trap
Recursive DFS on a big grid can go rows × cols deep →
StackOverflowError. Use BFS or anArrayDequestack. - trap
Check bounds before
grid[nr][nc], and loop over every vertex as a start, or disconnected parts are silently skipped. - trap
Directed cycle check needs 3 colours: only an edge into a gray (on-path) vertex is a cycle. A diamond is not.
- pro tip
Seed the queue with every source (rotten oranges, gates, zeros): one BFS instead of one per source.
- pro tip
"Fewest moves" puzzles (words, genes, dice boards, knights) are BFS on an implicit graph: states = vertices, moves = edges.
Shaky on a card? Open the chapter or flip its recall cards.