Lessons 16–20 · About 60 min per lesson
Graphs, grids and connectivity
Use BFS and DFS to find what is reachable from a starting point.
Lesson breakdown
- Lesson 16
Represent an undirected graph with adjacency lists and include isolated nodes.
- Lesson 17
Implement DFS with visited and an explicit stack.
- Lesson 18
Use a queue for BFS and record unweighted distances.
- Lesson 19
Find all connected components in a four-neighbour grid.
- Lesson 20
Check disconnected nodes, cycles and revisits.
Worked example
There are 4 nodes and edges 1–2 and 2–3. Which nodes can node 1 reach?
How to solve it
BFS reaches 1, 2 and 3 at distances 0, 1 and 2. Node 4 has no edges and is unreachable.
Assignment
Count four-connected regions of dots in a grid with hash-mark walls. Report the region count and largest size.
Check your result
Rows "..#", "##.", "#.." → 2 regions, largest 3. All walls → 0 0.