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:

  1. Initial state: Start at (0, 0) pointing east (0, +1). Mark (0, 0) as visited immediately and record matrix[0][0] as the first output element.
  2. Passable squares: A coordinate (r, c) can be entered if and only if 0 <= r < m, 0 <= c < n, [r, c] does not appear in blocked, and (r, c) has not been visited earlier in the walk.
  3. 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.
  4. 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, where m = len(matrix) and n = len(matrix[0]) (every row has length n).
  • -10^9 <= matrix[r][c] <= 10^9
  • 0 <= len(blocked) <= m * n - 1
  • Every [r, c] in blocked is distinct, lies within 0 <= r < m and 0 <= c < n, and [0, 0] is never in blocked.

Step-by-step walkthrough

  1. Understand the movement and stopping rules

    We are given an m x n grid of integers matrix and a list of obstacle coordinates blocked, where each entry is [row, col]. A walker starts on the top-left cell (0, 0) facing right, records matrix[0][0], and repeats one rule on every step:

    1. Look one cell ahead in the current facing direction.
    2. 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.
    3. Otherwise, rotate 90 degrees clockwise (right -> down -> left -> up -> right) and check again, trying at most all 4 directions from the current cell.
    4. 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 blocked is 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.

  2. 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 obstacle X, down is outside the grid, left (1, 0) is already visited, and up (0, 1) is also X. 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 - 1 moves. - Each move inspects at most 4 neighboring cells, plus 4 final checks when the walker gets trapped. - Total work is proportional to m * n, which for m, n <= 100 is at most around 40,000 tiny checks.

  3. 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 - 1 by 0 .. n - 1 matrix boundaries. 2. It is a blocker from blocked. 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 n boolean table closed[row][col], mark all blockers True before the walk begins, and flip each visited cell to True the 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]
    
  4. 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_idx is just (dir_idx + 1) % 4 (where % is the remainder operator, wrapping 3 + 1 = 4 back around to 0).

    On each step we loop turns over 0, 1, 2, 3 and test (dir_idx + turns) % 4: - Starting at turns = 0 is essential: the walker checks its current direction first so it keeps going straight whenever possible, and after turning it remembers the new dir_idx instead of resetting to right. - Checking up to turns = 3 handles 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 -1
    
  5. Trace Example 2 step by step

    Let's trace matrix = [[5, 8, 9], [15, 18, 19], [25, 28, 29]] with blocked = [[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_cols inside a for loop 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 marking closed[0][1] = True would accidentally block column 1 in every row!

  6. 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 the m x n closed table and marking the b blockers takes O(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 most m * n iterations; each iteration checks at most 4 neighboring coordinates in O(1) time.
  • Space: O(m * n). The closed boolean grid stores m * n booleans, and the output list visited_values holds at most m * n integers.

Edge cases

  • 1 x 1 matrix ([[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^9 to 10^9): Cell numbers are only appended to visited_values and 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 than m * n - len(blocked) elements. Always stop when choose_direction finds no open neighbor.
  • Resetting the direction to right on every step (or always turning): choose_direction must check turns = 0 (current dir_idx) first, and dir_idx must 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 setting closed[0][1] = True marks column 1 closed 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 blocked is empty): Maintain top, bottom, left, and right indices and traverse one outer rectangle per iteration in O(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 Python set instead of a 2D boolean array. If the walk gets trapped after k steps on a huge sparse grid, time and extra space become O(b + k) instead of O(m * n), at the cost of higher constant factors from tuple hashing when m, 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, and right = n - 1 — and sweep right across top, down right, left across bottom (guarded by if top < bottom so a single remaining row is not read twice), and up left (guarded by if left < right so a single remaining column is not read twice), then move all four walls inward by 1. Because those four integers replace the closed grid, auxiliary memory drops to O(1).
  • How would you adapt your implementation if each forced turn rotated 90 degrees counter-clockwise rather than clockwise? Replace DIRECTIONS with 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). Because choose_direction simply steps forward through DIRECTIONS using (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 while loop ends, closed[r][c] is True for every obstacle and every visited square, and False everywhere else. A single O(m * n) nested loop over (r, c) collecting [r, c] pairs where not closed[r][c] returns every unreached open square in row-major order without any extra lookup table.

Follow-up questions

Similar questions

More Temu interview questions

All 4 Temu questions →