Learn / Graphs

Grid graphs

A grid is a graph whose vertices are cells and whose edges join neighbouring cells. Flood fills and island marking are DFS; anything about the fewest steps is BFS, and starting BFS from many cells at once (all rotten oranges, all zeros) finds every cell's distance to the nearest source in one pass.

How to recognise it

  • A 2D grid of characters or numbers.
  • Regions, borders, distances or spreading over time.
  • Moves like a knight, or a maze with walls.

Cells as vertices

for each direction (dr, dc) in up, down, left, right:
    nr, nc = r + dr, c + dc
    if inside the grid and passable and not visited: visit (nr, nc)

Vertices, edges, adjacency lists and the other words used here are on the Structures page.

ProblemSearchStart
flood fillDFSthe clicked cell
enclaves, surrounded regionsDFSevery border cell
rotting oranges, 01 matrixBFSevery source cell at once
maze, knightBFSthe start

A multi-source BFS is just BFS with several cells in the queue at the start, all at distance 0.

Common mistakes

  • Checking the bounds after reading the cell.
  • Marking cells visited only when they leave the queue, so they are added twice.

Problems

0 of 8 solved

Check yourself

To find each cell's distance to the nearest 0, where does BFS start?

For surrounded regions, which O's survive?

How do you compare island shapes for 'distinct islands'?