Lab: Grid Walks and Matrix Rotation
Traverse rectangular 2D grids by rows, columns, diagonals and spiral rings, catch Python silent negative-index wrap-around bugs, zero rows and columns in place with marker cells, and rotate an n x n matrix 90 degrees clockwise in place.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: walk columns and group diagonals on rectangular grids
- Step 2: predict, then expose Python silent negative-index bug
- Step 3: walk spiral rings and zero rows and columns in place
- Step 4: verify matrix rotation with Hypothesis
- Check your understanding
- Apply it
- Review prompt
Lessons of Arrays & Strings
- How a Python List Grows Concept · 20 min
- A Cost Table for Lists and Strings Concept · 15 min
- In-Place Moves: Reverse, Rotate, Partition, Cyclic Sort Worked example · 30 min
- Building Strings Without Quadratic Traps Worked example · 15 min
- Lab: Grid Walks and Matrix Rotation Lab · 25 min
- Check: Array and String Drills Knowledge check · 8 questions
What you will learn
- Traverse 2D grids by rows, columns, diagonals and neighbors without index errors.
Prerequisites: Complexity Analysis
01. Goal and setup
Two-dimensional grids stored as grid[r][c] invite off-by-one and silent-wrap bugs, because beginners treat grid as a flat 1D array, swap row and column bounds (range(len(grid)) vs range(len(grid[0]))), or assume grid[-1][0] throws an error when stepping past row 0. This lab proves four core principles of 2D indexing: (1) the row count R = len(grid) and the column count C = len(grid[0]) are independent on rectangular grids; (2) diagonal coordinates satisfy linear invariants r - c and r + c; (3) spiral walks and in-place rewrites must track which cells they have already output or changed; and (4) a 90-degree clockwise rotation of an n x n matrix splits cleanly into a transpose (swap(matrix[r][c], matrix[c][r])) plus reversing every row in O(1) extra space.
Simplification note: in Python, a 2D list[list[int]] is a list of pointers to separate row lists (which can even have unequal lengths unless validated). Numerical code on multi-megabyte matrices uses contiguous flat arrays or NumPy views for cache speed, whereas nested list[list[int]] is the standard representation for general grid algorithms and interview problems.
Environment: Python 3.12.13 with pytest 9.2.0 and hypothesis 6.170.17 in an isolated virtual environment.
mkdir grid-lab && cd grid-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pytest hypothesis02. Step 1: walk columns and group diagonals on rectangular grids
Start grid_ops.py with two traversals on a rectangular 2 x 3 grid (R = 2 rows, C = 3 columns). The first index always selects the row (0 <= r < rows) and the second selects the column (0 <= c < cols), so walking column c from top to bottom holds c fixed while iterating r across range(rows). Using range(cols) or writing grid[c][r] can pass on a square 3 x 3 test matrix and then crash with IndexError or read the wrong cells on the rectangular 2 x 3 grid!
Now trace the two diagonal families below: moving down-right adds +1 to both r and c, so r - c remains constant along every main diagonal (top-left to bottom-right). Moving down-left adds +1 to r and subtracts 1 from c, so r + c remains constant along every anti-diagonal (top-right to bottom-left). Note that abs(r - c) would wrongly merge opposite diagonals like (0, 1) and (1, 0).
grid[r][c]: r - c (main): r + c (anti):
c=0 1 2 c=0 1 2 c=0 1 2
r=0 [1, 2, 3] r=0 [ 0, -1, -2] r=0 [0, 1, 2]
r=1 [4, 5, 6] r=1 [ 1, 0, -1] r=1 [1, 2, 3]def walk_columns(grid: list[list[int]]) -> list[list[int]]:
rows = len(grid)
cols = len(grid[0]) if rows else 0
return [[grid[r][c] for r in range(rows)] for c in range(cols)]
def group_diagonals(
grid: list[list[int]],
) -> tuple[dict[int, list[int]], dict[int, list[int]]]:
main_diags: dict[int, list[int]] = {}
anti_diags: dict[int, list[int]] = {}
for r, row in enumerate(grid):
for c, val in enumerate(row):
main_diags.setdefault(r - c, []).append(val)
anti_diags.setdefault(r + c, []).append(val)
return main_diags, anti_diagspython -c "import grid_ops as g; print(g.walk_columns([[1, 2, 3], [4, 5, 6]]))"[[1, 4], [2, 5], [3, 6]]03. Step 2: predict, then expose Python silent negative-index bug
Look at count_hash_neighbors_buggy(board, 0, 0) below before running it on board = ["...", "..#", "#.#"]. Notice (0, 0) has '.' to its right (0, 1) and '.' below (1, 0)—zero # neighbours in reality! Predict before running: will calling count_hash_neighbors_buggy(board, 0, 0) raise IndexError, return 0, or silently return a wrong count? Append these two functions and rotate_90_clockwise to grid_ops.py, then run it.
def count_hash_neighbors_buggy(grid: list[str], r: int, c: int) -> int:
count = 0
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
if grid[r + dr][c + dc] == "#":
count += 1
return count
def count_hash_neighbors_safe(grid: list[str], r: int, c: int) -> int:
rows, cols = len(grid), len(grid[0])
count = 0
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "#":
count += 1
return count
def rotate_90_clockwise(matrix: list[list[int]]) -> None:
n = len(matrix)
for r in range(n):
for c in range(r + 1, n):
matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
for row in matrix:
row.reverse()
if __name__ == "__main__":
rect = [[1, 2, 3], [4, 5, 6]]
print("columns:", walk_columns(rect))
m_diag, a_diag = group_diagonals(rect)
print("main_diags(r-c):", dict(sorted(m_diag.items())))
print("anti_diags(r+c):", dict(sorted(a_diag.items())))
board = ["...", "..#", "#.#"]
print("buggy at (0,0):", count_hash_neighbors_buggy(board, 0, 0))
print("safe at (0,0):", count_hash_neighbors_safe(board, 0, 0))
sq = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotate_90_clockwise(sq)
print("rotated 90 cw:", sq)python grid_ops.pycolumns: [[1, 4], [2, 5], [3, 6]]
main_diags(r-c): {-2: [3], -1: [2, 6], 0: [1, 5], 1: [4]}
anti_diags(r+c): {0: [1], 1: [2, 4], 2: [3, 5], 3: [6]}
buggy at (0,0): 1
safe at (0,0): 0
rotated 90 cw: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]Look at buggy at (0,0): 1! Why did Python not raise IndexError? Because negative indices are legal in Python and count backwards from the end of a sequence: r + dr = -1 read board[-1][0] (the # at the bottom-left corner), and c + dc = -1 read board[0][-1] (the right edge of row 0). Always guard every neighbour read with 0 <= nr < rows and 0 <= nc < cols—and make sure you write nr < rows and nc < cols rather than swapping them!
What if you needed 8-directional neighbours (including diagonals) instead of 4 orthogonal ones? You would expand the offsets tuple to all (dr, dc) pairs in (-1, 0, 1) x (-1, 0, 1) excluding (0, 0), keeping the exact same 0 <= nr < rows and 0 <= nc < cols boundary guard.
04. Step 3: walk spiral rings and zero rows and columns in place
A spiral order reads the outer ring of a grid clockwise, then the next ring in. spiral_order keeps four bounds, top, bottom, left and right, with this invariant: every cell outside the box they enclose has been output once, and no cell inside has. Each walk outputs one edge and moves that bound one step inward.
The while condition is checked only at the start of a lap, but the first two walks can use up the last row or column. On a 1 x 4 grid, top passes bottom after the top row; without if top <= bottom, the bottom-row walk reads row 0 again, backwards. A 4 x 1 grid needs if left <= right, and a 3 x 4 grid needs the first guard on lap 2 (below). Lap 1 alone is the boundary order. Create spiral_zeroes.py with part 1.
0 -> 1 -> 2 -> 3 lap 1, the boundary: 0 1 2 3 13 23 22 21 20 10
v
10 11 -> 12 13 lap 2: 11 12; now top = 2 > bottom = 1, so the
^ v first guard skips the bottom-row walk
20 <- 21 <- 22 <- 23def spiral_order(grid: list[list[int]], one_lap: bool = False) -> list[int]:
if not grid or not grid[0]:
return []
top, bottom, left, right = 0, len(grid) - 1, 0, len(grid[0]) - 1
out: list[int] = []
while top <= bottom and left <= right:
for c in range(left, right + 1): # top row, left to right
out.append(grid[top][c])
top += 1
for r in range(top, bottom + 1): # right column, downwards
out.append(grid[r][right])
right -= 1
if top <= bottom: # a row is still left
for c in range(right, left - 1, -1): # bottom row, backwards
out.append(grid[bottom][c])
bottom -= 1
if left <= right: # a column is still left
for r in range(bottom, top - 1, -1): # left column, upwards
out.append(grid[r][left])
left += 1
if one_lap:
break
return out
def boundary_order(grid: list[list[int]]) -> list[int]:
return spiral_order(grid, one_lap=True)Next, a task that writes while it reads: for every original 0, set its whole row and column to 0. zero_while_scanning clears both at once, but the scan then meets zeros it wrote itself and cannot tell them from original ones. Predict before running: how much of the runner grid z, with one 0 in its top row, survives?
Scanning a copy fixes this, but it costs a second grid when you only need to know which rows and columns to clear. set_zeroes_sets records them in two sets (O(R + C) extra space), then writes. set_zeroes_in_place uses O(1) extra space by keeping that record in the grid itself: grid[r][0] = 0 marks "clear row r" and grid[0][c] = 0 marks "clear column c". Pass 1 writes these marks over row 0 and column 0, so two booleans first record whether those had a zero of their own. Append part 2 and run it.
def zero_while_scanning(grid: list[list[int]]) -> None:
rows, cols = len(grid), len(grid[0])
for r in range(rows):
for c in range(cols):
if grid[r][c] == 0:
for k in range(cols):
grid[r][k] = 0
for k in range(rows):
grid[k][c] = 0
def set_zeroes_sets(grid: list[list[int]]) -> None:
zero_rows = {r for r, row in enumerate(grid) if 0 in row}
zero_cols = {c for row in grid for c, v in enumerate(row) if v == 0}
for r, row in enumerate(grid):
for c in range(len(row)):
if r in zero_rows or c in zero_cols:
row[c] = 0
def set_zeroes_in_place(grid: list[list[int]]) -> None:
rows, cols = len(grid), len(grid[0])
row0_had_zero = 0 in grid[0]
col0_had_zero = any(grid[r][0] == 0 for r in range(rows))
for r in range(1, rows): # pass 1: write marks into row 0 and column 0
for c in range(1, cols):
if grid[r][c] == 0:
grid[r][0] = 0
grid[0][c] = 0
for r in range(1, rows): # pass 2: clear inner cells that have a mark
for c in range(1, cols):
if grid[r][0] == 0 or grid[0][c] == 0:
grid[r][c] = 0
if row0_had_zero: # pass 3: row 0 and column 0 go last
for c in range(cols):
grid[0][c] = 0
if col0_had_zero:
for r in range(rows):
grid[r][0] = 0
if __name__ == "__main__":
g = [[10 * r + c for c in range(4)] for r in range(3)]
print("grid: ", g)
print("spiral: ", spiral_order(g))
print("boundary:", boundary_order(g))
print("1 x 4: ", spiral_order([[1, 2, 3, 4]]))
print("4 x 1: ", spiral_order([[1], [2], [3], [4]]))
for fn in (zero_while_scanning, set_zeroes_sets, set_zeroes_in_place):
z = [[4, 0, 7, 2], [3, 9, 6, 8], [5, 1, 6, 7]]
fn(z)
print(f"{fn.__name__}:", z)python spiral_zeroes.pygrid: [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23]]
spiral: [0, 1, 2, 3, 13, 23, 22, 21, 20, 10, 11, 12]
boundary: [0, 1, 2, 3, 13, 23, 22, 21, 20, 10]
1 x 4: [1, 2, 3, 4]
4 x 1: [1, 2, 3, 4]
zero_while_scanning: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
set_zeroes_sets: [[0, 0, 0, 0], [3, 0, 6, 8], [5, 0, 6, 7]]
set_zeroes_in_place: [[0, 0, 0, 0], [3, 0, 6, 8], [5, 0, 6, 7]]zero_while_scanning wiped all 12 cells: the rest of row 0 cleared columns 2 and 3, and the new 0 in column 1 of each lower row cleared that row. The other two agree. Pass order matters in set_zeroes_in_place: pass 2 reads the marks, so row 0 and column 0 are cleared after it. Clear row 0 first and every grid[0][c] looks like a mark: z would become [[0, 0, 0, 0], [3, 0, 0, 0], [5, 0, 0, 0]].
When not to use markers: the marker code is harder to read and to get right, and it must write into the caller's grid. If the original must stay unchanged, you would copy it first, an O(R x C) cost, while the set version can simply build a new grid. For a 1,000 x 1,000 grid the sets hold at most 2,000 indices, so keep them unless the task forbids extra memory.
Create test_spiral_zeroes.py. Its random grids hold values 0..3, so zeros in row 0 and column 0 are common, and @example adds fixed 1 x n and n x 1 cases.
from hypothesis import example, given
from hypothesis import strategies as st
from spiral_zeroes import (
boundary_order,
set_zeroes_in_place,
set_zeroes_sets,
spiral_order,
)
sizes = st.integers(min_value=1, max_value=6)
grids = st.tuples(sizes, sizes).flatmap(
lambda shape: st.lists(
st.lists(st.integers(0, 3), min_size=shape[1], max_size=shape[1]),
min_size=shape[0],
max_size=shape[0],
)
)
@given(sizes, sizes)
def test_spiral_reads_each_cell_once(rows: int, cols: int) -> None:
grid = [[r * cols + c for c in range(cols)] for r in range(rows)]
assert sorted(spiral_order(grid)) == list(range(rows * cols))
def test_boundary_is_first_lap_of_spiral() -> None:
grid = [[10 * r + c for c in range(4)] for r in range(3)]
ring = 2 * 3 + 2 * 4 - 4 # cells on the edge of a 3 x 4 grid
assert boundary_order(grid) == spiral_order(grid)[:ring]
@given(grids)
@example([[0]])
@example([[1, 0, 2, 3]])
@example([[1], [0], [2]])
@example([[1, 2, 3], [0, 4, 5], [6, 7, 8]])
def test_in_place_matches_sets(grid: list[list[int]]) -> None:
expected = [row[:] for row in grid]
set_zeroes_sets(expected)
set_zeroes_in_place(grid)
assert grid == expectedpytest -v test_spiral_zeroes.pytest_spiral_zeroes.py::test_spiral_reads_each_cell_once PASSED [ 33%]
test_spiral_zeroes.py::test_boundary_is_first_lap_of_spiral PASSED [ 66%]
test_spiral_zeroes.py::test_in_place_matches_sets PASSED [100%]05. Step 4: verify matrix rotation with Hypothesis
Notice in rotate_90_clockwise that the transpose loop iterates for c in range(r + 1, n): (strictly above the main diagonal) so each pair is swapped once—if c started at 0, every pair would be swapped twice and the transpose would undo itself. Why does transpose followed by row.reverse() rotate 90 degrees clockwise? Track a concrete cell (0, 2) (top-right corner 3 in a 3 x 3 grid): transposing sends (0, 2) to (2, 0) (bottom-left), and reversing row 2 moves column 0 to column 2, landing at (2, 2) (bottom-right)—matching the general clockwise mapping (r, c) -> (c, n - 1 - r).
When NOT to rotate in place: if the input grid is rectangular (R != C), an in-place square transpose is impossible because dimensions swap from R x C to C x R; you must allocate a new C x R grid ([[grid[R - 1 - r][c] for r in range(R)] for c in range(C)]). Create test_grid.py and verify with Hypothesis that four 90-degree rotations always restore the original matrix for n = 0..12.
from hypothesis import given
from hypothesis import strategies as st
from grid_ops import count_hash_neighbors_safe, rotate_90_clockwise
@given(st.integers(min_value=0, max_value=12))
def test_rotate_four_times_restores_matrix(n: int) -> None:
mat = [[r * n + c for c in range(n)] for r in range(n)]
orig = [row[:] for row in mat]
for _ in range(4):
rotate_90_clockwise(mat)
assert mat == orig
def test_safe_neighbors_on_edges() -> None:
board = ["...", "..#", "#.#"]
assert count_hash_neighbors_safe(board, 0, 0) == 0
assert count_hash_neighbors_safe(board, 2, 2) == 1pytest -v test_grid.pytest_grid.py::test_rotate_four_times_restores_matrix PASSED [ 50%]
test_grid.py::test_safe_neighbors_on_edges PASSED [100%]06. Check your understanding
07. Apply it
Add the inverse of spiral_order to spiral_zeroes.py: spiral_fill(values: list[int], rows: int, cols: int) -> list[list[int]] writes values into a new rows x cols grid in spiral order, reusing the four bounds and both guards. Verify with Hypothesis that spiral_fill(spiral_order(g), R, C) == g for random grids up to 8 x 8. Then add rotate_90_counterclockwise(matrix: list[list[int]]) -> None to grid_ops.py, test it on 0 x 0, 1 x 1 and 4 x 4 matrices in pytest, and verify with Hypothesis that rotating clockwise followed by rotating counter-clockwise always restores the original square matrix.
With dynamic arrays, immutable strings, and 2D matrices mastered, move on to constant-time lookup structures in Hashing & Hash Tables and Stacks, Queues & Deques.
08. Review prompt
Without looking back:
- Why does forgetting
0 <= nr < rows and 0 <= nc < colscause a wrong answer at(0, 0)instead of crashing in Python? - Which index expression stays constant along a main diagonal vs an anti-diagonal?
- Which grid shapes need each
ifguard inspiral_order, and why doesset_zeroes_in_placeclear row 0 and column 0 last? - Write down the two in-place steps for rotating an
n x nmatrix 90 degrees clockwise, and explain why the transpose inner loop starts atr + 1.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.