Graphs · Exercise 56 of 100

Depth-first search on a matrix

To explore a connected patch in a matrix, start at a cell in the patch and use depth-first search to follow unvisited neighbors with the same value. Mark each cell on entry to avoid counting it again when you return along a branch. The allowed neighbor directions determine which cells belong to the patch.

Try it yourself

A matrix has rows 1101, 0100, 0110 and 1001 from top to bottom. Starting at the top-left 1, how many cells does DFS visit if it follows only 1s sharing a side?

One-step hint

Shade the top-left 1, then extend the shading across shared sides to other 1s. Count each square only the first time you shade it.

Worked solution
  1. Visit the two 1s at the left of the top row, then follow the second column down through the next two rows.
  2. One more 1 lies to the right in the third row. All remaining 1s lack a shared side with this patch, so DFS visits 2 + 1 + 2 = 5 cells.
DSA compiler