Graph Theory37 sections · 1633 units
Open in Course

Counting Islands

From Pixels to Geography

In Section 22, you learned how to count connected components in graphs.

Now you will apply that to grids. This is widely considered the most "must-know" graph problem in existence. The grid represents a map. Land cells ('11') are nodes. Two land cells are connected if they are adjacent (up, down, left, right). Each connected component is an island. You count components by running DFS from each unvisited land cell and marking all reachable cells as visited.