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

  1. Lesson 16

    Represent an undirected graph with adjacency lists and include isolated nodes.

  2. Lesson 17

    Implement DFS with visited and an explicit stack.

  3. Lesson 18

    Use a queue for BFS and record unweighted distances.

  4. Lesson 19

    Find all connected components in a four-neighbour grid.

  5. 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.