Pattern

Grid

A 2D array is an implicit graph over cells; the fix is naming what an edge means before choosing DFS, BFS, or a 2D DP.

What it is

A grid problem treats every cell as a node in an implicit graph, where two cells are connected if they're adjacent (orthogonally, or with diagonals allowed) and satisfy some rule about their values. Once you see that, the technique is whichever graph tool fits: DFS/BFS flood fill to find connected components, multi-source BFS to compute distance-to-nearest-something, or backtracking DFS to trace a constrained path through the grid. A smaller slice of grid problems isn't graph search at all but a 2D dynamic program, where a cell's answer is built from its up/left/diagonal neighbors' already-computed answers.

When it applies

Tells in the problem

The classic mistake

The recurring bug is running a separate search from every cell or every individual source instead of recognizing that a single multi-source search (or one reversed search) answers the whole grid at once — this shows up as accidentally writing an O((rows·cols)²) solution when a linear one exists, because the naive framing ("for each cell, find its nearest gate") looks correct but throws away the shared work between neighboring cells. The second common bug is marking a cell visited when it's dequeued rather than when it's enqueued, which lets the same cell enter the queue many times and can blow up both time and (for backtracking DFS) correctness if the mark represents "in use." Before coding, ask whether the search should start from one cell or from every relevant cell at once, and mark state the moment a cell is scheduled for visiting, not when it's finally processed.

Questions to start with

All 12 grid questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.