Pattern 4 — Index Math & Matrix Walks
Grids look intimidating, but here's the secret: a grid is just a list of lists, and most grid problems are solved by getting the row-and-column arithmetic right — not by clever tricks.
The idea, in one line
A grid is rows stacked on rows. You reach any cell with grid[row][col], and the whole job is picking which row and column to visit next. That's index math.
How to spot it
The input is a 2D grid, image, or table, and the task uses words like:
- rotate — turn the whole grid 90°
- transpose — flip rows and columns
- diagonal — walk the corner-to-corner line
- spiral — read around the edges, winding inward
Two facts that unlock most of it
- Transpose: the cell at (r, c) moves to (c, r) — rows and columns swap.
- Rotate 90° clockwise: transpose first, then reverse each row.
- A main-diagonal cell is simply where row == col.
See it work
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
# Transpose: cell (r, c) -> (c, r)
def transpose(m):
return [[m[r][c] for r in range(len(m))] for c in range(len(m[0]))]
# Rotate 90 clockwise = transpose, then reverse each row
def rotate_cw(m):
return [row[::-1] for row in transpose(m)]
print(rotate_cw(grid)) # [[7,4,1],[8,5,2],[9,6,3]]
# Main diagonal: cells where row == col
print([grid[i][i] for i in range(len(grid))]) # [1, 5, 9]Read it top to bottom: transpose swaps every (r, c) with (c, r); rotating is just that swap followed by reversing each row; and the diagonal is every cell where the row number equals the column number.
Advanced — spirals and off-by-one bugs
Spiral and boundary walks use four moving edges — top, bottom, left, and right — that shrink inward after each pass. It's the two-pointer idea from earlier, just in 2D.
Grounded in the official Python docs (nested lists / data structures)
All lessons in Logic Building Bootcamp
- Pattern 1 — Counting how often things appear
- Pattern 2 — Two Pointers
- Pattern 3 — Sliding Window
- Pattern 4 — Index Math & Matrix Walks
- OOP Essentials — Classes, Inheritance, Magic Methods, Decorators