Graphs and DFS: Number of Islands

A graph is things (nodes) and links between them (edges). In Python, store it as an adjacency dict: {"a": ["b", "c"], "b": ["a"]}. A grid is a graph too: each cell links to its four neighbours.

Depth-first search (DFS) goes as deep as it can before backing up. Use it to count connected pieces: start a DFS from every unvisited node, and count how many times you start.

DFS is often written with recursion, but Python stops at about 1000 nested calls with RecursionError. A big grid of land is deeper than that. Use an explicit stack instead: a list you append to and pop from. Mark a node as seen when you push it. It is O(nodes + edges).

Exercise: finish count_islands. The grid is a list of strings, 1 is land and 0 is water. Land cells that touch up, down, left or right form one island. Return the number of islands. The speed test is one huge island, so recursion will fail. Press Check to run the tests.