0
Challenge · 52Graphs

Grids are graphs

Graphsused in ~90% of apps

Half the graph problems you will be asked do not mention graphs at all. They give you a grid, and once you see that a cell is a node and a neighbouring cell is an edge, the code you already have applies unchanged.

Core idea. A grid is a graph you never have to build. Every cell is a node, and its neighbours are the cells directly beside it, so the adjacency list is computed rather than stored. Everything else, the seen set, the stack or queue, the traversal, is identical to what you would write for a graph of numbered nodes.
Playground, this isn't a screenshot
counting islands, one cell at a time
land
land
land
land
land
land
land
land
islands found
1
found unvisited land at row 0, column 0. That is island number 1
step 1 of 9

Four directions, never diagonals. That single choice decides how many islands there are.

↑ play a little first, then dig in