Clockwise Grid Walk Around Obstacles and Visited Cells
Arrays & HashingAuto-graded · 26 test casesLast updated
Simulate a clockwise inward walk over a grid with obstacle cells, turning on edges, obstacles and visited cells, and stopping when every direction is closed.
You are given a rectangular grid of integers and a list of obstacle cells. Starting at the top-left corner, you walk across the grid in a clockwise, inward-spiralling pattern, and you must report the values of the cells in the order you step on them.
With no obstacles, the walk is the familiar spiral: along the top row to the right, down the right column, back along the bottom row to the left, up the left column, and then inward around the remaining cells. Obstacles change this: the walk never enters an obstacle cell and instead turns clockwise, exactly as it does at the grid boundary or at a cell it has already stepped on. One function must handle both the obstacle-free and the obstacle case.
Task
Implement walk_spiral_with_obstacles(grid, obstacles), which returns the list of values visited, in visiting order.
gridis a list ofmrows, each withnintegers.obstaclesis a list of[row, col]pairs, each naming an obstacle cell.
Rules
- Row
0is the top row and column0is the leftmost column. From(r, c): right is(r, c + 1), down is(r + 1, c), left is(r, c - 1), up is(r - 1, c). A clockwise turn changes right to down, down to left, left to up, and up to right. - A cell is available if it lies inside the grid, is not an obstacle, and has not been visited yet.
- The walk starts on
(0, 0)facing right. That cell counts as visited and its value is output first. - At each step, look at the cell next in the current facing direction. If it is available, move onto it and output its value. Otherwise turn clockwise by 90 degrees and look again, trying at most four directions in total (the current one plus up to three turns). The first direction whose next cell is available becomes the new facing direction, and the walk moves one cell that way.
- If none of the four directions leads to an available cell, the walk ends. Open cells that were never reached are not output.
- Obstacle cells are never output.
Constraints
1 <= m, n <= 100, wherem = len(grid)andn = len(grid[0]); every row has lengthn.-10^9 <= grid[r][c] <= 10^90 <= len(obstacles) <= m * n - 1- All obstacle cells are inside the grid and pairwise distinct, and
[0, 0]is never an obstacle.
Examples
Example 1
Input: walk_spiral_with_obstacles([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [])
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Example 2
Input: walk_spiral_with_obstacles([[1, 2, 3], [4, 5, 6]], [[0, 1]])
Output: [1, 4, 5, 6, 3]
Example 3
Input: walk_spiral_with_obstacles([[1, 2, 3, 4], [5, 6, 7, 8]], [[1, 3]])
Output: [1, 2, 3, 4]
Hints
Hint 1
Do not shrink top/bottom/left/right boundaries: obstacles make the unvisited area non-rectangular. Simulate the walk cell by cell instead.
Hint 2
Keep one boolean grid meaning 'cannot enter', pre-filled with the obstacles and updated whenever you visit a cell. Then a single test (in bounds and not marked) covers all three reasons to turn.
Hint 3
Store the heading as an index into the list right, down, left, up. At each step try headings (d + t) % 4 for t = 0..3, and only commit the heading when a move succeeds. If all four fail, stop.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Boundary-shrinking spiral code assumes the unvisited region is always a rectangle, and obstacles break that assumption. So we simulate the walk directly.
Three kinds of cells all cause the same reaction (turn clockwise): cells outside the grid, obstacles, and visited cells. We merge the last two into one boolean grid, closed, pre-filled with the obstacles and updated as we visit cells. A neighbour is usable exactly when it is in bounds and not closed.
Directions are stored in clockwise order (right, down, left, up), so a clockwise turn is just d + 1 modulo 4. At each step:
- For
t = 0..3, consider heading(d + t) % 4. - The first heading whose next cell is usable becomes the new heading. Move there, mark the cell closed and output its value.
- If none of the four headings works, stop.
Why it is correct
- The loop over
tis exactly the rule "check, otherwise turn clockwise, at most four directions". Updating the heading only when a move succeeds means the walk keeps facing its last real direction and tries to continue straight first. - Without obstacles, the unvisited cells always form a rectangle and the walk follows its outer edge. At a corner the cell ahead is outside or visited, one clockwise turn points along the next side, and the walk ends after exactly
m * ncells, giving the ordinary spiral. - With obstacles, several turns in one step may be needed (for example three turns, which amounts to a left turn). The four-direction loop handles this with no special case. Turning twice (reversing) never succeeds, because the cell behind is the one just left, which is visited, or is outside the grid at the start.
- Each move enters a never-visited cell, so there are at most
m * nmoves and the walk must terminate. Unreachable open cells are simply never output, so we must not use "visited count equals open cell count" as a stop condition.
Complexity
- Time: O(m * n + b), where b is the number of obstacles. There are at most
m * nmoves, each trying at most 4 directions. - Space: O(m * n) for the closed grid and the output.
Reference solution
from typing import List
def walk_spiral_with_obstacles(grid: List[List[int]], obstacles: List[List[int]]) -> List[int]:
m = len(grid)
n = len(grid[0])
closed = [[False] * n for _ in range(m)]
for r, c in obstacles:
closed[r][c] = True
# Clockwise order: right, down, left, up.
dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
r = c = d = 0
closed[0][0] = True
out = [grid[0][0]]
while True:
moved = False
for t in range(4):
nd = (d + t) % 4
dr, dc = dirs[nd]
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and not closed[nr][nc]:
d = nd
r, c = nr, nc
closed[r][c] = True
out.append(grid[r][c])
moved = True
break
if not moved:
return out