When to use grid traversal patterns
Use these patterns when you have:
- A 2D array or map and a question about connected regions: "how many islands", "the size of the biggest area", "fill this region".
- A need to move around a grid: a path from one cell to another, the shortest path through a maze, rotting oranges spreading each minute.
- A layout question about the matrix itself: print it in spiral order, rotate it, transpose it, or set whole rows and columns to zero.
- Any picture, board or map: pixels in an image, squares on a chessboard, tiles in a game.
Use something else when:
- The cells are not laid out on a regular grid, such as cities joined by roads: use a graph with an adjacency list.
- You only need sums over rectangles: use 2D prefix sums.
- Each cell's answer depends on the cells before it (the cheapest path with only right and down moves): use dynamic programming.
There is nothing to import. A grid is a list of lists (or a flat array). The traversal is a loop and, for flood fill, a queue or a stack.
How grid traversal works
A grid is a graph. Each cell is a node, and its up, down, left and right neighbours are its edges. That means everything you know about BFS and DFS applies, with the neighbours coming from arithmetic instead of an adjacency list.
Keep a list of direction offsets, loop over it, and check the bounds before reading a neighbour.
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] # down, up, right, left
Three patterns cover most matrix questions:
- Flood fill (connected regions). Scan every cell. When you find an unvisited cell of the right kind, count a new region and spread out from it with BFS or DFS, marking every connected cell visited. Because visited cells are skipped, each region is counted once.
- Boundary walk (spiral order). Keep four boundaries: top, bottom, left and right. Walk one side, move that boundary inwards, then turn.
- Layout tricks (rotate, transpose). Rotating a square 90° clockwise is a transpose (swap each cell with its mirror across the main diagonal) followed by reversing each row. No second matrix is needed.
A cell is marked visited when it is added to the queue, not when it is taken out. Otherwise the same cell can be added several times by different neighbours.
Try it
Pick one of the three problems, then press Run and step through. Rows are separated by /.
Matrix and grid traversal
Step 1 of 8 · Press Space to play, arrow keys to stepRows of 0 and 1 separated by /, for example 110/110/001
Map (1 = land, 0 = water)
Scanning row by row
A 1 is land and a 0 is water. Count the islands: groups of land cells that touch up, down, left or right. Scan the grid, and flood out from each new piece of land.
- islands:
- 0
- cells visited:
- 0
- cells in the grid:
- 20
Every technique touches each cell a constant number of times, so the work grows with the number of cells (rows times columns).
Things to try:
- Count islands, "Three islands": the map
11000/11000/00100/00011has 3 islands. The flood fill visits all 7 land cells once and skips the 13 water cells, out of 20 cells in total. Try "Diagonal touching" (100/010/001): there are 3 islands, because cells that only touch at a corner are not connected. - Spiral order, "3 by 3":
1 2 3/4 5 6/7 8 9comes out as1 2 3 6 9 8 7 4 5. Try "3 by 4" to see the boundaries shrink on a rectangle. - Rotate 90° clockwise, "3 by 3": three swaps transpose the matrix and three row reversals finish the turn, 6 operations in total, with no second matrix.
Grid traversal operations
Count islands (flood fill).
- Make a visited table (or change visited land to water, if allowed).
- For every cell, skip it unless it is unvisited land.
- Count one island, mark the cell visited and put it in a queue.
- Take a cell from the queue. For each of its four neighbours that is inside the grid, is land and is unvisited, mark it and add it to the queue.
- Repeat step 4 until the queue is empty, then continue the scan.
Spiral order.
- Set
top = 0,bottom = rows - 1,left = 0,right = cols - 1. - Walk the top row left to right, then do
top++. Walk the right column top to bottom, then doright--. - If
top <= bottom, walk the bottom row right to left, then dobottom--. - If
left <= right, walk the left column bottom to top, then doleft++. Repeat.
Rotate 90° clockwise, in place. Swap m[i][j] with m[j][i] for every j > i, then reverse every row.
Interview fact. Cell (i, j) of an n × n matrix ends at (j, n - 1 - i) after a clockwise turn. Say that formula and then show that transpose plus reverse produces it.
Grid traversal time complexity
R is the number of rows and C is the number of columns.
| Task | Time | Extra memory |
|---|---|---|
| Count islands (BFS or DFS) | O(R × C) | O(R × C) worst case for the visited table and queue |
| Spiral order | O(R × C) | O(1) besides the output |
| Rotate a square in place | O(n²) | O(1) |
| Shortest path in a maze (BFS) | O(R × C) | O(R × C) |
Every cell is visited a constant number of times, so the work always grows with the number of cells, not with the number of regions or the length of any path.
Grid traversal vs other approaches
R × C is the number of cells.
| What you need | BFS or DFS flood fill | Union-find | Dynamic programming | Check every pair of cells |
|---|---|---|---|---|
| Count connected regions once | O(R × C), simple | O(R × C) with extra code | Not applicable | O((R × C)²) |
| Regions that change as cells are added | Rerun each time | Near O(1) per update | Not applicable | Far too slow |
| Shortest path, every move costs 1 | BFS: O(R × C) | Not applicable | Possible but unusual | Far too slow |
| Cheapest path, only right and down moves | Possible | Not applicable | O(R × C), simplest | Far too slow |
The bold cells show where each wins. Flood fill is the default for one-off questions about regions and paths. Union-find wins when cells keep getting added.
How to explain grid traversal in an interview
- Say first: "a grid is a graph, and each cell has up to four neighbours."
- Show the direction array and say you check the bounds first.
- Say when you mark cells visited: "when I add them to the queue, so none is added twice".
- Choose BFS or DFS and say why: BFS for shortest paths, DFS or BFS for plain connectivity, and an explicit stack if the grid is large enough that recursion could overflow.
- State both costs: O(rows × cols) time and O(rows × cols) memory in the worst case, and say how you would reduce it.