Read a grid in spiral order by walking four walls: across the top, down the right, back along the bottom, up the left, then shrink inward.
▼The problem
LeetCode 54 (Medium). Given an m × n matrix, return all of its elements in spiral order: clockwise around the outside from the top-left corner, then inward, ring by ring.
Examples (LeetCode's): [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5] (walked in scene 6) and [[1,2,3,4],[5,6,7,8],[9,10,11,12]] → [1,2,3,4,8,12,11,10,9,5,6,7] (its second ring is a single row, which is what the guards are for: scene 7).
The solution
def spiral_order(matrix):
res = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
res.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
res.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
res.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
res.append(matrix[r][left])
left += 1
return resTranscript
Spiral Matrix. Given a grid of numbers, M rows by N columns, return every number in spiral order: clockwise around the edge from the top left, then inward, ring by ring.
Take one to nine in a three by three grid. The spiral reads one, two, three, six, nine, eight, seven, four, and last, five in the middle. Three rows of one to twelve go around the edge, then end on five, six, seven.
The simple way drives like a robot mower: go straight, and turn right at the edge or at a mowed cell. It works, but a second grid of check marks remembers every mowed cell: M times N extra space.
The trick: you only need four edges. Top, bottom, left and right fence in the unmowed part. Mow the top row, then pull top down. Mow the right column, then pull right in. Then the bottom row leftward, pulling bottom up, and the left column upward, pulling left in. That's one ring. Repeat while top is at most bottom, and left at most right.
In code, four variables hold the edges. Each loop mows one ring: a pass per side, then a step inward. Two passes get a check: the bottom row runs only if top is still at most bottom, the left column only if left is at most right.
Walk one to nine. Top row: one, two, three, and top moves down. Right column: six, nine, and right moves in. Bottom row: eight, seven. Left column: four. The edges meet in the middle: the last ring is just five.
Why the checks? Take three rows of four. After the outer ring, one row is left: six, seven. Mow it, and top drops below bottom. Without the check, the bottom row would run back over it and read six again. The check skips it.
Each cell is mowed once, so the time is order M times N. The only memory is four edges: constant extra space.
Mow the edge, pull it in, repeat. That's Spiral Matrix.