Walking a grid: spiral order and turning it round
🌍 In real life. A guard checking a building floor by floor walks the outer corridor first, round all four sides, then the next corridor in, and so on until the middle. And when you turn a photo on your phone a quarter turn, its top row of pixels becomes its right-hand column.
Both are walks over a 2D grid that are not row by row, and both come up often in interviews (the spiral is LeetCode 54, the turn is LeetCode 48).
The idea in one sentence: walk a grid in a spiral by keeping four edges (top, bottom, left, right), walking along one side and then moving that edge in; turn a square grid a quarter clockwise by swapping it across its diagonal and then reversing every row.
Its words:
- ring (layer): one loop of cells around the grid; a 3 × 3 grid has an outer ring and a middle cell
- edges:
top,bottom,left,right, the rows and columns not yet walked - transpose: swap
grid[r][c]withgrid[c][r], mirroring the grid across its diagonal
Step by step, the spiral of a 3 × 3 grid:
- Along the top row, left to right: 1 2 3. That row is done, so
topmoves down. - Down the right column: 6 9.
rightmoves left. - Along the bottom row, right to left: 8 7.
bottommoves up. - Up the left column: 4.
leftmoves right. - The edges now close in on the middle: 5.
Why it is correct. Each walk takes one whole side of the current ring and then moves that edge in, so a cell, once taken, is outside the edges for good: nothing is taken twice. The loop runs while top <= bottom and left <= right, so it doesn't stop while a cell is still inside. The two if checks matter when only a single row or column is left: without them, that row would be walked a second time on the way back (try a 1 × 3 grid).
What it costs, by counting. Every cell is appended once and every edge moves at most R + C times in all: O(R × C) time, and no extra memory besides the answer.
Turning a square a quarter clockwise. Two easy passes instead of one hard one:
- transpose: for every pair
r < c, swapgrid[r][c]andgrid[c][r]: rows become columns - reverse each row: the first column is now the last
Both are done in place, n² / 2 swaps plus n / 2 per row: O(n²), the least possible, since every cell moves. In one line of Python, without in place:
[list(row) for row in zip(*grid[::-1])].
def rotate(grid):
n = len(grid)
for r in range(n):
for c in range(r + 1, n):
grid[r][c], grid[c][r] = grid[c][r], grid[r][c]
for row in grid:
row.reverse()
photo = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotate(photo)
for row in photo:
print(row)
print([list(row) for row in zip(*[[1, 2], [3, 4]][::-1])])Mistakes and edge cases.
- Missing the two checks. For a single row
[[1, 2, 3]]the spiral withoutif top <= bottomgives[1, 2, 3, 2, 1]: the row is walked back. - Swapping every pair in the transpose. Looping
cover all ofrange(n)swaps each pair twice, which puts it back: the grid doesn't change. Start atc = r + 1. - Reversing the wrong thing. Reversing the order of the rows (
grid.reverse()) after the transpose turns the grid anticlockwise instead. - An empty grid.
grid[0]raisesIndexError: list index out of range; return[]first whennot grid. - Rotating a rectangle in place. A 2 × 3 grid becomes 3 × 2, so it can't be turned in place; build a new list instead.
Quiz
What does this print?
grid = [[1, 2], [3, 4], [5, 6]] out = [] top, bottom, left, right = 0, 2, 0, 1 while top <= bottom and left <= right: for c in range(left, right + 1): out.append(grid[top][c]) top += 1 for r in range(top, bottom + 1): out.append(grid[r][right]) right -= 1 if top <= bottom: for c in range(right, left - 1, -1): out.append(grid[bottom][c]) bottom -= 1 if left <= right: for r in range(bottom, top - 1, -1): out.append(grid[r][left]) left += 1 print(out)You transpose a square grid, then reverse every row. Which way has it turned?
- A quarter turn clockwise
- A quarter turn anticlockwise
- Half a turn
What does the spiral walk of an R × C grid cost?
- O(R × C): every cell is taken once
- O(R + C): one walk per edge
- O((R × C)²)
rotate should turn [[1, 2], [3, 4]] into [[3, 1], [4, 2]], but it gives [[2, 1], [4, 3]], only a mirror image. Which line is wrong?
def rotate(grid): n = len(grid) for r in range(n): for c in range(n): grid[r][c], grid[c][r] = grid[c][r], grid[r][c] for row in grid: row.reverse()
Coding tasks
Write
spiral(grid): the items of the grid in spiral order, clockwise from the top-left corner. Return[]for an empty grid.Write
rotate(grid)that turns a square grid a quarter clockwise in place (change the lists you are given; return nothing).