Grid Walk With Clockwise Redirects at Walls and Obstacles
Arrays & HashingAuto-graded · 27 test casesLast updated
Tests grid simulation by traversing a matrix in a right-biased clockwise walk that turns at boundaries, visited cells, and blocked positions until no move is possible.
You have an m x n grid of integers. Your task is to collect its values in the order a clockwise spiral walk visits them, extended to handle obstacle cells that redirect the walker.
Walk rules
The walker begins at the top-left corner (0, 0), facing right. That starting cell is immediately collected.
At every subsequent step the walker inspects the cell directly ahead. If that cell is reachable, the walker moves into it and collects its value. If not, the walker rotates 90 degrees clockwise and inspects the next candidate, repeating until a reachable cell is found or all four directions have been checked. The walker commits to the first direction that leads to a reachable cell.
A cell is reachable if all three of the following hold:
- It lies within the grid bounds.
- It has not been visited yet.
- It is not an obstacle.
The walk ends the moment all four directions fail. Any unvisited, non-obstacle cells the walk never reaches are simply omitted from the output.
Obstacles are never collected and never visited; they exist only to redirect or stop the walker.
Direction conventions
- Right:
(r, c) → (r, c + 1) - Down:
(r, c) → (r + 1, c) - Left:
(r, c) → (r, c − 1) - Up:
(r, c) → (r − 1, c)
Clockwise rotation order: right → down → left → up → right → …
Obstacles
Obstacles are supplied as a list of [row, col] pairs. A grid with an empty obstacle list produces the plain clockwise spiral order; both cases are handled by the same function.
Constraints
1 <= m, n <= 100, wherem = len(grid)andn = len(grid[0]); every row has exactlyncells.-10^9 <= grid[r][c] <= 10^90 <= len(obstacles) <= m * n - 1- Every pair in
obstaclesis inside the grid, all pairs are distinct, and[0, 0]is never an obstacle.
Examples
Example 1
Input: spiral_with_blockers([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [])
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Example 2
Input: spiral_with_blockers([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[1, 1]])
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5]
Example 3
Input: spiral_with_blockers([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[0, 1]])
Output: [1, 4, 7, 8, 9, 6, 3]
Hints
Hint 1
Instead of computing spiral layers with shrinking boundaries, simulate the walk step by step with three pieces of state: current position, current direction, and which cells are still available to enter.
Hint 2
Obstacles and already-visited cells block movement in exactly the same way. Store both in one boolean grid so you only need one reachability check — no special cases for obstacles versus visited.
Hint 3
At each step, try the current direction first, then rotate clockwise up to three more times. Moving in the first direction that works and stopping the entire walk when all four fail directly encodes the problem rules.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why simulate instead of using shrinking boundaries
The classic four-boundary approach works only for complete rectangles. The moment obstacles appear, the current ring can have holes, and the boundary arithmetic breaks down. Simulation avoids this entirely: the walker just looks one step ahead and decides whether to continue or turn.
State
Three variables carry all the information needed:
(r, c)— current positiond— current direction as an index into[right, down, left, up]avail— a boolean grid whereFalsemeans "cannot be entered"
Obstacles and visited cells are treated identically. Both make a cell unreachable, so both are stored in the same avail grid. Obstacles are set to False before the walk starts; each cell the walker enters is also set to False immediately. This single check eliminates any need to distinguish the two cases.
Per-step logic
At each step, try direction indices d, d+1, d+2, d+3 (mod 4). This is "continue straight; if blocked, rotate clockwise; if still blocked, rotate again; and once more if needed." The walker moves in the first direction that leads to an available cell and updates d to that direction. If all four fail, the walk ends and the collected values are returned.
The order matters: straight first, then clockwise rotations. When multiple neighbours are open, this tie-break is what produces the correct spiral path.
Correctness
Multiple turns per step. Some positions require two or three consecutive turns before a free cell is found (see example 3, where the walker at (2, 0) facing down must turn three times to face right). An implementation that turns only once and gives up stops too early.
The fourth candidate always fails harmlessly. The reverse direction always points back to the cell just left, which is already visited. At the very first step it points outside the grid. So checking all four directions is safe and keeps the code a direct match of the rules.
No blockers → plain spiral. Without obstacles, visited cells always form complete outer rings. A single right turn always locates the next ring cell. The walk terminates only when every cell has been collected, producing the classic spiral.
Termination. Every move marks one more cell unavailable. The pool of available cells strictly shrinks, so the walk makes at most m × n − len(blocked) − 1 moves before all four directions fail.
Values are collected exactly once. A cell is appended only when it is entered, and it can only be entered while it is still True in avail. Entering it flips it to False, preventing any future visit. Obstacles are initialized to False and are never appended.
Edge cases
- 1 × 1 grid: output is
[matrix[0][0]]. All four directions are outside the grid, so the walk ends immediately. - Single row: the walker goes right to the last cell. There, right and down are outside, left is visited, and up is outside — walk ends.
- Single column: right fails at
(0, 0), so the walker turns down and follows the column. - Walker boxed in by obstacles and edges: only
matrix[0][0]is collected. - Unreachable open cells: the walk stops where the rules say and does not jump to isolated regions.
- Values in
[-10^9, 10^9]: the code uses a separate boolean grid rather than writing a sentinel into the matrix, which avoids both value collisions and mutation of the caller's input.
Complexity
- Time:
O(m · n)— buildingavailisO(m · n), marking obstacles isO(len(blocked)), and each of the at mostm · nsteps does at most 4 constant-time checks. - Space:
O(m · n)for theavailgrid, plus the output list of at mostm · nentries.
Reference solution
from typing import List
def spiral_with_blockers(matrix: List[List[int]], blocked: List[List[int]]) -> List[int]:
m = len(matrix)
n = len(matrix[0])
# avail[r][c] is True iff (r, c) can still be entered.
# Obstacles and visited cells both set this to False.
avail = [[True] * n for _ in range(m)]
for r, c in blocked:
avail[r][c] = False
# Clockwise direction vectors: right, down, left, up.
dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
r = c = 0
d = 0 # index into dirs; 0 = facing right
avail[0][0] = False # starting cell is immediately visited
out = [matrix[0][0]]
while True:
moved = False
# Try current direction, then up to three clockwise rotations.
for t in range(4):
nd = (d + t) % 4
nr = r + dirs[nd][0]
nc = c + dirs[nd][1]
if 0 <= nr < m and 0 <= nc < n and avail[nr][nc]:
d = nd
r, c = nr, nc
avail[r][c] = False
out.append(matrix[r][c])
moved = True
break
if not moved:
return out