Traverse every cell in a grid using BFS (level-by-level) or DFS (depth-first). Β β± Time
O(mΓn)Β πΎ SpaceO(mΓn)
A grid is just a graph in disguise β each cell (i, j) is a node, and its neighbours are the 4 adjacent cells (up/down/left/right, or diagonals for 8-directional). Apply BFS or DFS with a visited set of (row, col) tuples, and always check bounds and visited before processing.
Neighbours of (i, j):
(i-1, j) β up
(i+1, j) β down
(i, j-1) β left
(i, j+1) β right
Boundary check: 0 β€ i < rows and 0 β€ j < cols
Grid (4Γ6):
0 1 2 3 4 5
6 7 8 9 10 11
12 13 14 15 16 17
18 19 20 21 22 23
BFS from (0,0): visits row by row, left to right
0 β 1 β 6 β 2 β 7 β 12 β ... (by Manhattan distance from origin)
DFS from (0,0): dives deep before coming back
0 β 1 β 2 β 3 β 4 β 5 β 11 β 17 β 23 β ...
Grid traversal is the two-dimensional generalisation of graph traversal, fundamental to image processing (flood fill), pathfinding (A*, Dijkstra on grids), and cellular automaton simulation (Conway's Game of Life).
- Template pattern: BFS for shortest path in grid, DFS for exhaustive exploration (islands, connected regions)
- Store visited as a set of
(i, j)tuples or modify the grid in-place (grid[i][j] = '#'to mark visited β common trick to save space) - "Number of Islands" (LeetCode 200) = count BFS/DFS calls from unvisited '1' cells
- Add boundary and visited checks at dequeue time (BFS) or at the top of DFS to handle edge cases cleanly
- For 4-directional movement: use
dirs = [(0,1),(0,-1),(1,0),(-1,0)]and loop
- Number of islands / connected regions (LeetCode 200, 695)
- Shortest path in a maze (BFS β LeetCode 1091)
- Flood fill (image paint bucket tool β LeetCode 733)
- Game grid pathfinding (Pac-Man, chess, Minesweeper)
- Rotten oranges / spreading problems (multi-source BFS)
- BFS β the general BFS algorithm
- DFS β the general DFS algorithm
- Shortest Path β BFS for shortest path
- N Provinces β connected components in a graph