Python 3D Academyবাংলা

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] with grid[c][r], mirroring the grid across its diagonal

Step by step, the spiral of a 3 × 3 grid:

  1. Along the top row, left to right: 1 2 3. That row is done, so top moves down.
  2. Down the right column: 6 9. right moves left.
  3. Along the bottom row, right to left: 8 7. bottom moves up.
  4. Up the left column: 4. left moves right.
  5. 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:

  1. transpose: for every pair r < c, swap grid[r][c] and grid[c][r]: rows become columns
  2. 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])])
The top row 1 2 3 became the right-hand column, read from the top.

Mistakes and edge cases.

  • Missing the two checks. For a single row [[1, 2, 3]] the spiral without if top <= bottom gives [1, 2, 3, 2, 1]: the row is walked back.
  • Swapping every pair in the transpose. Looping c over all of range(n) swaps each pair twice, which puts it back: the grid doesn't change. Start at c = 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] raises IndexError: list index out of range; return [] first when not 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

  1. 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)
  2. 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
  3. 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)²)
  4. 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

  1. Write spiral(grid): the items of the grid in spiral order, clockwise from the top-left corner. Return [] for an empty grid.

  2. Write rotate(grid) that turns a square grid a quarter clockwise in place (change the lists you are given; return nothing).