Logic Building Bootcamp · Lesson 4 of 5

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.

By Shahriyar · Updated

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:

Two facts that unlock most of it

See it work

▸ try it
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

  1. Pattern 1 — Counting how often things appear
  2. Pattern 2 — Two Pointers
  3. Pattern 3 — Sliding Window
  4. Pattern 4 — Index Math & Matrix Walks
  5. OOP Essentials — Classes, Inheritance, Magic Methods, Decorators