Drill

ProblemsPython › patterns

Read the floor plan in a spiral

hardpatternsGridsArraysPython

A stocktake walks a warehouse grid from the outside in, clockwise, so the counter never crosses their own path.

spiral_walk(bays: list<list<int>>) → list<int>

Solve it in the editor →

Where you start

def spiral_walk(bays: list[list[int]]) -> list[int]:
    

Worked examples

CallResult
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

The same problem in another language

More patterns problems in Python