Graphs & Networks
Graph BFS
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
shortest pathfewest stepsminimum movesunweightednearestspread
Practice
Drill this pattern with an AI trainer — reply only with Hint, Next, Lost, or paste your code.
Ask yourself
- Shortest path / fewest steps in an UNWEIGHTED graph?
- Spread / infection / multi-source expansion?
- Queue, track distance per layer.
Classic problem
Shortest Path (BFS) — Given an unweighted graph of n nodes and edges, find the shortest path from start to target. BFS guarantees the first time we reach the target is via the shortest route.
Input: n = 6, edges = [[0,1],[0,2],[1,3],[2,4],[3,5],[4,5],[3,4]], start = 0, target = 5
Output: 3 — the shortest path is 0 → 1 → 3 → 5 (or 0 → 2 → 4 → 5), 3 hops.
Common pitfalls
Marking visited at dequeue, not enqueue (dupes blow up).
Using BFS on a weighted graph (need Dijkstra).