Phase 1: Islands and Components — the same algorithm, different representation

You Already Know This

You already know how to count islands on a grid. You launch flood fill from each unvisited land cell and count the launches. Now here is the same problem — but the data comes as a list of edges instead of a grid. The algorithm does not change. Only the neighbor lookup changes.

Here is the key insight you may have missed about Number of Islands: a grid is just a graph in disguise. Each land cell '1' is a node. The four-directional adjacencies (up, down, left, right) are edges. The grid was a graph all along — it just had a costume on. Its edges were implicit (always to the four orthogonal neighbors). An adjacency list makes those edges explicit.

FIG. 1 — GRID WITH 2 COMPONENTS → GRAPH WITH 2 COMPONENTS. SAME STRUCTURE.

Graph (explicit edges)

012
Both have 2 components. The algorithm: scan each node, launch DFS from unvisited ones, count launches.

On a grid, “look up neighbors” means “check up/down/left/right.” On an adjacency list, “look up neighbors” means “iterate `graph[node]`.” The outer scan loop, the visited set, the launch count — everything is identical. Only that one operation changes.

When I first saw this problem after solving Number of Islands, I thought it was a trick question. “It is the same thing.” And it IS the same algorithm. But the moment I tried to implement it on an adjacency list instead of a grid, I fumbled the neighbor lookup. Grid neighbors are implicit (up/down/left/right — always four directions, always present). Graph neighbors are explicit (read graph[node] — could be none, could be ten). The algorithm is the same; the data access is different. That distinction matters more than I expected.

And there is a second algorithm entirely — one that does not explore at all. It processes edges instead of nodes. But first, let us verify you feel the DFS approach. The grid was trying to look special. Underneath its costume, it is just a graph with very regular edges.

Tap a node to see its adjacency list.