Read the floor plan in a spiral
A stocktake walks a warehouse grid from the outside in, clockwise, so the counter never crosses their own path.
- Start at the top left and move right along the top row.
- Then down the right edge, back along the bottom, up the left, and inwards.
- Every cell appears exactly once.
- An empty grid gives an empty walk.
spiral_walk(bays: list<list<int>>) → list<int>
Where you start
def spiral_walk(bays: list[list[int]]) -> list[int]:
Worked examples
| Call | Result |
|---|---|
spiral_walk([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) | [1, 2, 3, 6, 9, 8, 7, 4, 5] |
spiral_walk([[1, 2], [3, 4]]) | [1, 2, 4, 3] |
spiral_walk([[1, 2, 3]]) | [1, 2, 3] |
spiral_walk([[1], [2], [3]]) | [1, 2, 3] |
Hint
Track four edges — top, bottom, left, right. Walk one of them, then pull that edge in, and stop when they cross.
Reference solution in Python
def spiral_walk(bays: list[list[int]]) -> list[int]:
walk = []
if not bays:
return walk
top, bottom = 0, len(bays) - 1
left, right = 0, len(bays[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
walk.append(bays[top][c])
top += 1
for r in range(top, bottom + 1):
walk.append(bays[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
walk.append(bays[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
walk.append(bays[r][left])
left += 1
return walk