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.
| Problem | Search | Start |
|---|---|---|
| flood fill | DFS | the clicked cell |
| enclaves, surrounded regions | DFS | every border cell |
| rotting oranges, 01 matrix | BFS | every source cell at once |
| maze, knight | BFS | the 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
- Flood Filleasyguide ready
- Number of Enclavesmediumguide ready
- Rotting Orangesmediumguide ready
- 01 Matrixmediumguide ready
- Surrounded Regionsmediumguide ready
- Number of Distinct Islandsmediumguide ready
- Search in a Mazemediumguide ready
- Minimum Step by Knighthardguide ready