2D Grids & Matrix Traversal
Data Structures & Algorithms · Arrays & Strings · Intermediate · 20 min
Move around a grid with confidence: row/column indexing, neighbours with a direction array, spiral order with four shrinking walls, rotation, and flood fill.
A city map of blocks. You stand at (row, col) and each move is a small step north, south, east or west. Spiral order is walking the outer ring of the city, then the next ring inside, like peeling an onion.
The idea in everyday words
A cinema seat is named by row and seat number: row 3, seat 5. Asking for 'the seat in front of me' means row minus 1, same seat. A grid problem is just a list of rows, and every move is adding a small (row change, column change) pair. Flood fill is like spilling paint on one tile: it spreads to every touching tile of the same colour, and stops at walls.
Rows, columns and the grid[r][c] habit
A 2D grid in Python is a list of rows, and each row is a list:
grid = [
[1, 2, 3],
[4, 5, 6],
]
rows, cols = len(grid), len(grid[0])
print(rows, cols, grid[1][2]) # row 1, column 2 -> 6
grid[r][c]: first the row (up/down, like y), then the column (left/right, like x).rows = len(grid),cols = len(grid[0]).- A cell is in bounds when
0 <= r < rows and 0 <= c < cols. Check this before every neighbour access. - Create grids with a comprehension:
[[0] * cols for _ in range(rows)]. Never[[0] * cols] * rows, which repeats one row object.
To visit every cell, use two nested loops, rows outside, columns inside (row-major order):
grid = [[1, 2, 3], [4, 5, 6]]
for r in range(len(grid)):
for c in range(len(grid[0])):
print((r, c), grid[r][c])
Neighbours with a direction array
Writing four separate if blocks for up, down, left, right is long and error-prone. Instead, list the moves once:
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, right
def neighbours(grid, r, c):
out = []
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]):
out.append((nr, nc))
return out
g = [[0] * 3 for _ in range(3)]
print(neighbours(g, 0, 0)) # a corner has 2 neighbours
print(neighbours(g, 1, 1)) # the centre has 4
Need diagonals too? Add (-1, -1), (-1, 1), (1, -1), (1, 1) for 8 directions. One loop, one bounds check, no copy-paste bugs. This pattern powers flood fill, number of islands, BFS shortest paths on grids and game-of-life.
Spiral order: four walls closing in
Spiral order walks the outer ring clockwise, then the next ring inside, until every cell is visited.
Don't try to predict turns. Keep four walls: top, bottom, left, right. Each pass does four straight runs, and after each run the wall you just walked moves inward:
- left → right along
top, thentop += 1 - top → bottom along
right, thenright -= 1 - right → left along
bottom(iftop <= bottom), thenbottom -= 1 - bottom → top along
left(ifleft <= right), thenleft += 1
Stop when the walls cross. The two if checks matter for non-square grids: after the first two runs, there may be no row or column left to walk back along, and without the checks you would visit cells twice.
For a 3×3 grid of 1..9 the spiral is 1 2 3 6 9 8 7 4 5.
Rotate 90°: transpose, then reverse each row
Rotating an n×n matrix 90° clockwise looks hard cell by cell, but it is two easy moves:
- Transpose: swap
m[r][c]withm[c][r]for everyc > r(flip across the main diagonal). - Reverse each row.
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = len(m)
for r in range(n):
for c in range(r + 1, n):
m[r][c], m[c][r] = m[c][r], m[r][c]
for row in m:
row.reverse()
print(m) # [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Why it works: rotating clockwise sends the cell at (r, c) to (c, n - 1 - r). Transposing gives (c, r), reversing the row turns r into n - 1 - r. Breaking a hard transformation into two simple ones is a great interview habit. Counter-clockwise: transpose, then reverse the order of the rows.
Flood fill: spreading paint
Flood fill recolours a cell and every cell connected to it (up, down, left, right) that has the same original colour. It is the "paint bucket" tool.
The thinking: "paint this cell, then do the same for each same-coloured neighbour." Keep a stack (DFS) or queue (BFS) of cells still to process:
def flood_fill(grid, sr, sc, new):
old = grid[sr][sc]
if old == new:
return grid # nothing to do (and avoids looping forever)
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
grid[sr][sc] = new
stack = [(sr, sc)]
while stack:
r, c = stack.pop()
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == old:
grid[nr][nc] = new # paint when pushing, so no cell is pushed twice
stack.append((nr, nc))
return grid
print(flood_fill([[1, 1, 0], [1, 0, 0], [1, 1, 1]], 0, 0, 2))
Recolouring doubles as the visited mark. Each cell is painted at most once: O(rows × cols). Run flood fill from every unvisited land cell and count how many times you start: that is Number of Islands.
Step by step
- Set the walls:
3×3 grid [[1,2,3],[4,5,6],[7,8,9]]. top = 0, bottom = 2, left = 0, right = 2.
- Top row →:
Walk row 0 from col 0 to 2: 1, 2, 3. Row 0 is done, so top = 1.
- Right column ↓:
Walk col 2 from row 1 to 2: 6, 9. Column 2 is done, so right = 1.
- Bottom row ←:
top (1) ≤ bottom (2), so walk row 2 from col 1 down to 0: 8, 7. bottom = 1.
- Left column ↑:
left (0) ≤ right (1), so walk col 0 from row 1 up to 1: 4. left = 1.
- Inner ring:
Walls are now top = bottom = 1, left = right = 1: one cell left. Top run takes 5, then top = 2 > bottom and the loop ends. Result: 1 2 3 6 9 8 7 4 5.
Code example
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def spiral(m):
out = []
top, bottom, left, right = 0, len(m) - 1, 0, len(m[0]) - 1
while top <= bottom and left <= right:
out += [m[top][c] for c in range(left, right + 1)]; top += 1
out += [m[r][right] for r in range(top, bottom + 1)]; right -= 1
if top <= bottom:
out += [m[bottom][c] for c in range(right, left - 1, -1)]; bottom -= 1
if left <= right:
out += [m[r][left] for r in range(bottom, top - 1, -1)]; left += 1
return out
def rotate(m):
n = len(m)
for r in range(n):
for c in range(r + 1, n):
m[r][c], m[c][r] = m[c][r], m[r][c]
for row in m:
row.reverse()
return m
def flood_fill(grid, sr, sc, new):
old = grid[sr][sc]
if old == new:
return grid
grid[sr][sc] = new
stack = [(sr, sc)]
while stack:
r, c = stack.pop()
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == old:
grid[nr][nc] = new
stack.append((nr, nc))
return grid
print("spiral:", spiral([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
print("rotate:", rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
for row in flood_fill([[1, 1, 0], [1, 0, 0], [1, 1, 1]], 0, 0, 2):
print(row)Complexity
- Time: O(m × n) for spiral, rotate and flood fill: every cell is visited a constant number of times.
- Space: Spiral: O(1) besides the output. Rotate: O(1), in place. Flood fill: O(m × n) for the stack in the worst case.
Interview tips
Ask the shape questions up front: can the grid be empty? non-square? can I modify it in place?
Name your variables r, c, rows, cols, and write the bounds check as one helper or one line. It keeps you from mixing up axes under pressure.
For spiral order, explain the four-walls idea before coding; interviewers want to see that you avoided a fragile turn-by-turn simulation.
For flood fill or islands, state the complexity as O(rows × cols) and mention that recursion can hit Python's recursion limit on big grids, so an explicit stack or queue is safer.
Challenge: Spiral Matrix
Given an m × n matrix, return all its values in clockwise spiral order, starting from the top-left corner.
Example: spiral_order([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) → [1, 2, 3, 6, 9, 8, 7, 4, 5]
The matrix can be empty, a single row or a single column.
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Flood Fill (Easy)
- Spiral Matrix (Medium)
- Rotate Image (Medium)
- Number of Islands (Medium)
More in Arrays & Strings
Previous: Strings, Characters & Anagrams · Next: Linked Lists