Clockwise Spiral Traversal Around Grid Obstacles
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given a rectangular integer grid matrix with m rows and n columns along with a coordinate list blocked, simulate a clockwise spiral walk that turns away from obstacles and already-visited squares.
Implement the function:
def spiral_with_blockers(matrix: list[list[int]], blocked: list[list[int]]) -> list[int]:
Grid rows are indexed 0 through m - 1 from top to bottom, and columns are indexed 0 through n - 1 from left to right. Each element of blocked is a [row, col] pair marking an impassable obstacle cell.
The walk obeys the following rules:
- Initial state: Start at
(0, 0)pointing east(0, +1). Mark(0, 0)as visited immediately and recordmatrix[0][0]as the first output element. - Passable squares: A coordinate
(r, c)can be entered if and only if0 <= r < m,0 <= c < n,[r, c]does not appear inblocked, and(r, c)has not been visited earlier in the walk. - Stepping and clockwise rotation: To take each step from the current square, inspect the adjacent square in the current heading first. Whenever that neighbor is not passable, rotate the heading 90 degrees clockwise in the cycle
east (0, +1) -> south (+1, 0) -> west (0, -1) -> north (-1, 0) -> east (0, +1)and test the new neighbor, checking up to all four directions. Advance one cell along the first passable direction found, keep that direction as the active heading for the next step, mark the entered cell visited, and append its integer value to the result. - Stopping condition: As soon as none of the four cardinal neighbors around the current square is passable, halt immediately and return the recorded values. Obstacle values are never emitted, and any open squares that were sealed off and never reached are omitted.
Note that when blocked is empty, these exact rules visit all m * n entries in standard outward-to-inward clockwise spiral order.
Examples
Example 1
Input:
matrix = [[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34]]
blocked = []
Output:
[11, 12, 13, 14, 24, 34, 33, 32, 31, 21, 22, 23]
With zero obstacles, the cursor sweeps east across row 0, south down column 3, west across row 2, north to (1, 0), and finally east across the unvisited interior cells 22 and 23.
Example 2
Input:
matrix = [[5, 8, 9],
[15, 18, 19],
[25, 28, 29]]
blocked = [[0, 2], [2, 1]]
Output:
[5, 8, 18, 15, 25]
Starting at (0, 0), the cursor steps east to 8 at (0, 1). Because (0, 2) is an obstacle, one 90-degree clockwise turn points south into 18 at (1, 1). Moving south again hits obstacle (2, 1), so another clockwise turn points west into 15 at (1, 0). From (1, 0) facing west, west is off-grid, north (0, 0) is visited, and east (1, 1) is visited, so the third clockwise turn points south into 25 at (2, 0). At (2, 0) every neighbor is off-grid, visited, or blocked, ending the walk while 19 and 29 remain unreachable.
Example 3
Input:
matrix = [[7, 3, 1],
[6, 4, 2]]
blocked = [[0, 1], [1, 2]]
Output:
[7, 6, 4]
From (0, 0) facing east, obstacle (0, 1) forces an immediate clockwise turn south to 6 at (1, 0). Three clockwise turns at (1, 0) redirect the heading east to 4 at (1, 1), where (1, 2) and (0, 1) are obstacles, (1, 0) is visited, and row 2 is out of bounds, so traversal stops before ever reaching 1 at (0, 2).
Constraints
1 <= m, n <= 100, wherem = len(matrix)andn = len(matrix[0])(every row has lengthn).-10^9 <= matrix[r][c] <= 10^90 <= len(blocked) <= m * n - 1- Every
[r, c]inblockedis distinct, lies within0 <= r < mand0 <= c < n, and[0, 0]is never inblocked.
Step-by-step walkthrough
Understand the movement and stopping rules
We are given an
m x ngrid of integersmatrixand a list of obstacle coordinatesblocked, where each entry is[row, col]. A walker starts on the top-left cell(0, 0)facing right, recordsmatrix[0][0], and repeats one rule on every step:- Look one cell ahead in the current facing direction.
- If that cell is available (inside the matrix, not a blocker, and not yet visited), step onto it, record its value, and keep facing the same direction.
- Otherwise, rotate 90 degrees clockwise (
right -> down -> left -> up -> right) and check again, trying at most all 4 directions from the current cell. - If none of the 4 directions leads to an available cell, stop immediately and return the values collected so far.
Grid coordinates & clockwise turns: up (-1, 0) ^ left (0, -1) < + > right (0, +1) Turn order: right -> down -> left -> up -> right v down (+1, 0)Notice that when
blockedis empty, turning clockwise at the matrix border and at already-visited outer rings naturally traces the standard clockwise spiral! So one clean simulation solves both the plain spiral and the blocker follow-up.Why ring-peeling fails with obstacles (and why simulation is fast)
Without obstacles, a well-known shortcut peels rectangular outer layers using four shrinking wall pointers (
top,bottom,left,right). Obstacles break that shortcut completely because an impassable cell can force a turn in the middle of a row or seal off a corridor so some open squares are never visited at all:Example 3: matrix = [[7, 3, 1], obstacles at (0, 1) and (1, 2) marked X: [6, 4, 2]] [ 7 X 1 ] <- 1 at (0, 2) is never reached! [ 6 -> 4 X ] <- trapped at (1, 1)At
(1, 1)facing right: right(1, 2)is an obstacleX, down is outside the grid, left(1, 0)is already visited, and up(0, 1)is alsoX. The walker halts with[7, 6, 4].Simulating the walk directly is not only exact, it is already optimal: - Every successful move steps onto a brand-new cell, so there are at most
m * n - 1moves. - Each move inspects at most 4 neighboring cells, plus 4 final checks when the walker gets trapped. - Total work is proportional tom * n, which form, n <= 100is at most around40,000tiny checks.Unify blockers and visited cells into one `closed` grid
Look at the three reasons a neighbor cannot be entered: 1. It lies outside the
0 .. m - 1by0 .. n - 1matrix boundaries. 2. It is a blocker fromblocked. 3. The walker already visited it earlier.The walker reacts identically to all three: it refuses to step there and turns clockwise instead. That means we do not need separate lookup tables for blockers and visited cells. We can maintain a single
m x nboolean tableclosed[row][col], mark all blockersTruebefore the walk begins, and flip each visited cell toTruethe moment we land on it.from typing import List def is_available(row: int, col: int, closed: List[List[bool]]) -> bool: """Return True if (row, col) is inside the matrix and neither blocked nor visited.""" num_rows = len(closed) num_cols = len(closed[0]) # Bounds check uses < num_rows and < num_cols because grid indices are 0-based. if row < 0 or row >= num_rows or col < 0 or col >= num_cols: return False return not closed[row][col]Choose the next direction with modulo arithmetic
If we store the 4 direction offsets in clockwise order: -
0: right(0, +1)-1: down(+1, 0)-2: left(0, -1)-3: up(-1, 0)then rotating 90 degrees clockwise from
dir_idxis just(dir_idx + 1) % 4(where%is the remainder operator, wrapping3 + 1 = 4back around to0).On each step we loop
turnsover0, 1, 2, 3and test(dir_idx + turns) % 4: - Starting atturns = 0is essential: the walker checks its current direction first so it keeps going straight whenever possible, and after turning it remembers the newdir_idxinstead of resetting to right. - Checking up toturns = 3handles tight corners where 1 or 2 clockwise turns are still blocked (for example, 3 clockwise turns equals a 90-degree left turn).from typing import List DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] def choose_direction(row: int, col: int, dir_idx: int, closed: List[List[bool]]) -> int: """Return the first open clockwise direction index from dir_idx, or -1 if trapped.""" # Try turns = 0 first so the walker keeps going straight unless forced to turn. for turns in range(4): candidate_dir = (dir_idx + turns) % 4 d_row, d_col = DIRECTIONS[candidate_dir] next_row = row + d_row next_col = col + d_col if is_available(next_row, next_col, closed): return candidate_dir return -1Trace Example 2 step by step
Let's trace
matrix = [[5, 8, 9], [15, 18, 19], [25, 28, 29]]withblocked = [[0, 2], [2, 1]]:Initial grid (X = obstacles at (0, 2) and (2, 1)): col 0 col 1 col 2 [ 5 , 8 , X ] row 0 [ 15 , 18 , 19 ] row 1 [ 25 , X , 29 ] row 2 Step-by-step walk: 1. Start at (0, 0), facing right (dir 0). Record [5]. 2. At (0, 0) facing right: - turns=0 (right -> (0, 1)): available! Move to (0, 1), dir=0. Record [5, 8]. 3. At (0, 1) facing right: - turns=0 (right -> (0, 2)): closed (obstacle X) - turns=1 (down -> (1, 1)): available! Move to (1, 1), dir=1 (down). Record [5, 8, 18]. 4. At (1, 1) facing down: - turns=0 (down -> (2, 1)): closed (obstacle X) - turns=1 (left -> (1, 0)): available! Move to (1, 0), dir=2 (left). Record [5, 8, 18, 15]. 5. At (1, 0) facing left: - turns=0 (left -> (1,-1)): out of bounds - turns=1 (up -> (0, 0)): closed (already visited) - turns=2 (right -> (1, 1)): closed (already visited) - turns=3 (down -> (2, 0)): available! Move to (2, 0), dir=1 (down). Record [5, 8, 18, 15, 25]. 6. At (2, 0) facing down: - down & left: out of bounds; up (1, 0): visited; right (2, 1): obstacle X. - All 4 directions fail -> choose_direction returns -1 -> stop!Pay attention to how we allocate
closed: we append[False] * num_colsinside aforloop rather than writing[[False] * num_cols] * num_rows. Multiplying the outer list would make every row point to the same inner list in memory, so markingclosed[0][1] = Truewould accidentally block column1in every row!Assemble the complete solution
Put the helpers and the main simulation loop together.
from typing import Any, Dict, List, Optional, Set, Tuple # DIRECTIONS: (d_row, d_col) step offsets in clockwise order: # index 0 = right (0, +1), 1 = down (+1, 0), 2 = left (0, -1), 3 = up (-1, 0). DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] def is_available(row: int, col: int, closed: List[List[bool]]) -> bool: """Return True if (row, col) is inside the matrix and neither blocked nor visited.""" num_rows = len(closed) num_cols = len(closed[0]) # Bounds check uses < num_rows and < num_cols because grid indices are 0-based. if row < 0 or row >= num_rows or col < 0 or col >= num_cols: return False return not closed[row][col] def choose_direction(row: int, col: int, dir_idx: int, closed: List[List[bool]]) -> int: """Return the first open clockwise direction index from dir_idx, or -1 if trapped.""" # Try turns = 0 first so the walker keeps going straight unless forced to turn. for turns in range(4): candidate_dir = (dir_idx + turns) % 4 d_row, d_col = DIRECTIONS[candidate_dir] next_row = row + d_row next_col = col + d_col if is_available(next_row, next_col, closed): return candidate_dir return -1 def spiral_with_blockers(matrix: list[list[int]], blocked: list[list[int]]) -> list[int]: num_rows = len(matrix) num_cols = len(matrix[0]) # Phase 1: Build closed[r][c] (m x n booleans), True for blockers and visited cells. # Allocate each row separately so rows do not alias the same list object in memory. closed = [] for _ in range(num_rows): closed.append([False] * num_cols) for block_row, block_col in blocked: closed[block_row][block_col] = True # Phase 2: Start at top-left (0, 0) facing right (dir_idx = 0) and record it first. row = 0 col = 0 dir_idx = 0 closed[0][0] = True visited_values = [matrix[0][0]] # Phase 3: Advance one cell per step, turning clockwise at obstacles until trapped. while True: dir_idx = choose_direction(row, col, dir_idx, closed) # When all 4 neighbors are out of bounds, blocked, or visited, the walk stops. if dir_idx == -1: break d_row, d_col = DIRECTIONS[dir_idx] row += d_row col += d_col closed[row][col] = True visited_values.append(matrix[row][col]) return visited_values✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a small robot vacuum placed in the top-left corner of a tiled room, initially pointing right. It follows one simple rule: if the tile directly in front of it is inside the room, has no furniture on it, and has not been cleaned yet, roll forward onto that tile; otherwise, rotate 90 degrees to the right (clockwise) up to four times until you face an open tile, and power off the moment all four surrounding tiles are unavailable. Because the robot treats furniture (blockers) and already-cleaned tiles identically, we can track both in a single m x n boolean grid closed and cycle through the four directions using modulo arithmetic (wrapping (dir_idx + turns) % 4 around 0, 1, 2, 3 so 3 + 1 wraps back to 0).
Why does the classic spiral-matrix shortcut fail here? Standard spiral algorithms peel off rectangular outer rings using four shrinking wall pointers (top, bottom, left, right). As soon as even one blocker sits in the middle of a row or blocks a narrow passage, the path is no longer a neat sequence of concentric rectangles — the walker can turn early into the interior or get boxed into a corner while unvisited cells remain elsewhere. Simulating one cell at a time handles every obstacle layout cleanly without ever revisiting a cell.
Here is a tiny trace on matrix = [[7, 3, 1], [6, 4, 2]] with obstacles X at (0, 1) and (1, 2) (Example 3):
Grid: [ 7, X, 1 ]
[ 6, 4, X ]
(0,0) facing right -> (0,1) is X, turn down -> step to (1,0) [output: 7, 6]
(1,0) facing down -> down/left outside, up visited, turn 3x to right -> (1,1) [output: 7, 6, 4]
(1,1) facing right -> (1,2) is X, down outside, left visited, (0,1) is X -> stop!
Complexity
Let m be the number of rows (len(matrix)), n be the number of columns (len(matrix[0])), and b be len(blocked) (where b < m * n).
- Time:
O(m * n). Allocating them x nclosedtable and marking thebblockers takesO(m * n + b) = O(m * n)work. During the walk, every move lands on a cell that was never visited before and immediately marks it closed, so the loop executes at mostm * niterations; each iteration checks at most 4 neighboring coordinates inO(1)time. - Space:
O(m * n). Theclosedboolean grid storesm * nbooleans, and the output listvisited_valuesholds at mostm * nintegers.
Edge cases
1 x 1matrix ([[5]],blocked = []):(0, 0)is recorded immediately, all 4 neighbors are out of bounds, and the walk returns[5].- Single row or single column: The walker marches straight to the end of the line and stops once the remaining three directions are out of bounds and the cell behind it is visited.
- All cells except
(0, 0)blocked: Every neighbor of(0, 0)is closed on the very first check, so[matrix[0][0]]is returned. - Early termination leaving open cells unvisited: Obstacles can trap the walker in a dead end (such as
(2, 0)in Example 2 or(1, 1)in Example 3), and unreached open cells are rightly omitted. - Three consecutive clockwise turns at one cell: At tight corners like
(1, 0)in Examples 2 and 3, straight ahead, 1 turn, and 2 turns all fail, and the 3rd clockwise turn (equivalent to turning 90 degrees left) finds the open neighbor. - Negative and extreme cell values (
-10^9to10^9): Cell numbers are only appended tovisited_valuesand never used as flags or sentinel markers, so any integer value works safely.
Common mistakes
- Turning only once instead of trying up to four directions: Plain-spiral code often assumes a single 90-degree right turn always lands on an open cell. With blockers or narrow corridors, up to 3 clockwise turns can be needed, and if the 4th check also fails the walk must terminate.
- Looping a fixed
m * n - len(blocked)number of times: Because blockers can seal off parts of the matrix, the walk can legitimately finish with fewer thanm * n - len(blocked)elements. Always stop whenchoose_directionfinds no open neighbor. - Resetting the direction to
righton every step (or always turning):choose_directionmust checkturns = 0(currentdir_idx) first, anddir_idxmust persist across steps so the walker continues in its newly chosen direction. - Creating the grid with
[[False] * num_cols] * num_rows: In Python, multiplying a list of lists copies references to the same inner list (row aliasing), so settingclosed[0][1] = Truemarks column1closed in every row at once. - Swapping row and column deltas: Moving right increases the column (
(0, +1)), whereas moving down increases the row ((+1, 0)).
Alternative approaches
- Four-boundary ring peeling (only when
blockedis empty): Maintaintop,bottom,left, andrightindices and traverse one outer rectangle per iteration inO(1)extra space beyond the output list. While space-optimal for the plain spiral, it cannot handle arbitrary interior blockers because obstacles break rectangular symmetry. - Hash set of closed coordinates: Store
(row, col)tuples in a Pythonsetinstead of a 2D boolean array. If the walk gets trapped afterksteps on a huge sparse grid, time and extra space becomeO(b + k)instead ofO(m * n), at the cost of higher constant factors from tuple hashing whenm, n <= 100.
Follow-up questions
- If there are no obstacle cells at all, how can you produce the clockwise spiral using O(1) extra memory beyond the output list? Maintain four integer boundaries —
top = 0,bottom = m - 1,left = 0, andright = n - 1— and sweep right acrosstop, downright, left acrossbottom(guarded byif top < bottomso a single remaining row is not read twice), and upleft(guarded byif left < rightso a single remaining column is not read twice), then move all four walls inward by 1. Because those four integers replace theclosedgrid, auxiliary memory drops toO(1). - How would you adapt your implementation if each forced turn rotated 90 degrees counter-clockwise rather than clockwise? Replace
DIRECTIONSwith counter-clockwise offsets — for instance,[(0, 1), (-1, 0), (0, -1), (1, 0)]when starting facing right (or[(1, 0), (0, 1), (-1, 0), (0, -1)]if starting facing down). Becausechoose_directionsimply steps forward throughDIRECTIONSusing(dir_idx + turns) % 4, the rest of the simulation remains unchanged. - Suppose the caller also wants the coordinates of every non-obstacle cell that remained unvisited when the walk terminated. How would you compute them? After the
whileloop ends,closed[r][c]isTruefor every obstacle and every visited square, andFalseeverywhere else. A singleO(m * n)nested loop over(r, c)collecting[r, c]pairs wherenot closed[r][c]returns every unreached open square in row-major order without any extra lookup table.
Follow-up questions
- If there are no obstacle cells at all, how can you produce the clockwise spiral using O(1) extra memory beyond the output list?
- How would you adapt your implementation if each forced turn rotated 90 degrees counter-clockwise rather than clockwise?
- Suppose the caller also wants the coordinates of every non-obstacle cell that remained unvisited when the walk terminated. How would you compute them?
Similar questions
- Longest Consecutive Login Streaks
- Identify Missing Straight Rank
- Subset Next Greater Lookup
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses