Exercises — BFS — algorithm, queue-based, O(V+E), shortest path in unweighted graphs
The tiny graph we reuse in several problems is drawn once here so you can point at it:

Level 1 — Recognition
Goal: can you read a BFS trace and name its parts?
Recall Solution 1.1
WHAT: a queue. The discipline: FIFO (First-In-First-Out). WHY it matters: nodes added earlier (closer to ) leave earlier, so pops come out sorted by distance — that is exactly the "ring by ring" order from the parent note's stone-in-water picture.
Recall Solution 1.2
. WHY: distance counts edges walked, and you walk zero edges to stay where you start. This seeds every other distance: everything else is measured relative to this .
Recall Solution 1.3
It is DFS. It does not guarantee shortest paths, because a stack serves the newest node, so it plunges deep before finishing a level — the first arrival at a node may be via a long detour, not the fewest edges.
Level 2 — Application
Goal: run BFS by hand and produce distances and paths.
Recall Solution 2.1
Queue trace (mark visited at push):
| pop | pushes | queue after | dist set |
|---|---|---|---|
| init | 0 | [0] | |
| 0 | 1,2 | [1,2] | |
| 1 | 3 | [2,3] | |
| 2 | — (3 visited) | [3] | — |
| 3 | 4 | [4] | |
| 4 | — | [] | done |
Answer: .
WHY : node 3 is first discovered from level-1 node 1, so it lands on level 2 — the route 0→1→3 (2 edges) is captured, and node 2 (also level 1) finds 3 already visited and skips it.
Recall Solution 2.2
Parents from the trace: .
Walk backward from 4: . Reverse: 0, 1, 3, 4 (length 3 edges = ). ✓
WHY backward: each parent points one step toward the source along the BFS tree, so chaining parents is guaranteed to be a shortest route. See Shortest Path Tree.
Recall Solution 2.3
BFS on the implicit grid graph: the distance to equals the fewest unit moves. In an open grid with only U/D/L/R, that is the Manhattan distance . For : moves. WHY BFS works here: every move costs exactly 1 (unweighted), so first arrival = shortest — no adjacency list needed, neighbors computed on the fly. See Graph Representations — adjacency list vs matrix.
Level 3 — Analysis
Goal: reason about correctness, complexity, and structure.
Recall Solution 3.1
(a) Each vertex is pushed at most once → at most enqueues. (b) When a vertex is popped, we scan its out-edges once; summed over all vertices that is every directed edge once → edge scans. (c) , i.e. linear . WHY add, not multiply: the vertex loop and the edge scan are the same pass, not nested — you don't re-scan all edges for each vertex.
Recall Solution 3.2
No. The invariant: the queue always holds at most two consecutive levels and , with all level- nodes ahead of level- nodes. A later state puts a level-2 node behind level-3 nodes and spans no smaller level — impossible, because a level-2 node must have been dequeued before any level-3 node was reached. WHY this matters: this ordering is precisely what makes pops non-decreasing in distance, which is the whole proof of shortest-path correctness.
Recall Solution 3.3
Node 6 is never reached, so it is never pushed and visited[6] stays false. Conventionally (or a sentinel like ).
WHY: BFS only explores nodes connected to . To cover every node you run BFS again from each still-unvisited node — this is exactly how Connected Components are enumerated.
Level 4 — Synthesis
Goal: combine BFS with another idea to solve a new problem.
Recall Solution 4.1
(A), (B), (B). Now check edge 1-2: both are colored B — same color across an edge. So the 2-coloring fails; the triangle is not bipartite.
WHY parity coloring works: in a bipartite graph every edge joins an even level to an odd level. An odd cycle (length 3 here) forces two same-level neighbors to be adjacent, which BFS detects. See Bipartite Check.
Recall Solution 4.2
BFS ignores weights: it sees 0→1 as 1 edge, so it "reports" node 1 at edge-distance . But the cheapest cost is 0→2→1 , versus direct 0→1 . So the cheapest total cost is .
WHY BFS is wrong here: BFS minimizes number of edges, and fewer edges (0→1, one edge) is not cheaper. Use Dijkstra's Algorithm for non-negative weights, or 0-1 BFS if every weight is 0 or 1.
Recall Solution 4.3
Seed the queue with both sources at distance 0: push 0 and 4 first, . From 0: . From 4: . Then seconds. WHY multi-source works: initializing the queue with several 0-distance nodes makes BFS expand rings from all of them simultaneously; each node's distance is to its nearest source — the FIFO order still guarantees non-decreasing distances.
Level 5 — Mastery
Goal: design and prove, no scaffolding.
Recall Solution 5.1
Claim: if is dequeued before , then . Proof by the FIFO + push-rule. A node's distance is fixed when it is pushed by its popped parent: . Process parents in dequeue order with (induction hypothesis). Children of get distance and are pushed in that same order, so they sit in the queue sorted by parent distance. Since FIFO preserves push order, the next batch dequeued is again non-decreasing, and each child's distance its parent's — never smaller than anything already dequeued. Hence the global dequeue order is non-decreasing in . ∎ Consequence: the first time a node is reached, no route of fewer edges exists — that is the shortest-path guarantee.
Recall Solution 5.2
From Exercise 2.1: . The maximum is , achieved by node 4. WHY it's a legitimate BFS output: a single BFS from gives all at once, so the eccentricity of is just — no extra work.
Recall Solution 5.3
Method: delete from the graph (skip it in every neighbor loop, treat it as always-visited), then run one ordinary BFS from . Read ; if unreached, no valid path exists. WHY correct: removing makes every route BFS can find automatically avoid , and BFS on the reduced graph still returns fewest edges among the allowed routes. Complexity: still — one BFS pass, marking visited up front costs .
Recall Feynman recap
A grader could hand you any of these and the pattern is the same: BFS lays down rings of equal distance, the queue keeps the rings in order, and the first time you touch a node is the cheapest (in edges) you'll ever touch it. Everything past L2 is just noticing which problems secretly reduce to "count rings from a source": components, bipartite parity, multi-source fires, forbidden-node paths. If weights appear, BFS steps aside for Dijkstra.
Connections
- BFS — main note
- DFS — depth-first traversal
- Dijkstra's Algorithm
- 0-1 BFS
- Graph Representations — adjacency list vs matrix
- Connected Components
- Bipartite Check
- Shortest Path Tree