Skip to content
BytePatterns

Rotate In Place

Matrix & Grid: lesson 3 of 5

Mirror the diagonal, then flip each row.

Lesson 3 of 5 · 5 min

Rotate In Place

Step 1 of 10

A quarter turn clockwise sends row 0 up the right-hand edge: 1, 2, 3 end up stacked in the last column.

The Idea

A quarter turn clockwise sends row 0 up the right-hand edge. Getting there directly means juggling four cells at once.

Do it in two easy moves instead. Transpose — swap grid[r][c] with grid[c][r] — and rows become columns. Then reverse each row, and those columns end up on the correct side. No second grid, no index gymnastics.

Real-World Example

Photo viewers rotate large images with exactly this pair of passes, because allocating a second full-resolution buffer on a phone is what makes the app stutter. The same trick turns a landscape-only sensor feed upright in place.

The Code

def rotate(g):
    n = len(g)
    for r in range(n):
        for c in range(r + 1, n):      # upper triangle only, or you undo it
            g[r][c], g[c][r] = g[c][r], g[r][c]
    for row in g:
        row.reverse()                  # mirror each row left to right
    return g

print(rotate([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]]))             # [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Python

Your turn

Fill in the blank.

for r in range(n):
    for c in range(___, n):
        g[r][c], g[c][r] = g[c][r], g[r][c]

Mini quiz

1 / 3

What are the two moves of a clockwise rotation?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.