Read the Grid in a Spiral

MediumMatrix

Problem

A pick-and-place robot empties a tray laid out as an m × n grid. It starts at the top-left cell and moves clockwise in a spiral: across the top row, down the right column, back along the bottom row, up the left column, then the same pattern one ring further in, until every cell has been visited exactly once.

Return the values in the order the robot visits them.

Example 1

Input:
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output:
[1, 2, 3, 6, 9, 8, 7, 4, 5]

Outer ring 1 → 3 → 9 → 7 → 4, then the centre 5.

Example 2

Input:
grid = [[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]

Constraints

  • 1 ≤ m, n ≤ 100
  • -1000 ≤ grid[i][j] ≤ 1000

Hint

Show the first hint

Track the part of the grid that has not been visited yet as a rectangle.

Walkthrough

How to approach it

01Clarify before coding

  • Which direction first? Right along the top row, then clockwise.
  • Can the grid be a single row or a single column? Yes, and it must not repeat cells.
  • Should I modify the grid? No need: return a new list.

02Brute force

Simulate the robot with a direction vector and a visited matrix, turning right whenever the next cell is outside the grid or already visited.

Cost: O(m · n) time but O(m · n) extra memory for the visited flags. It works; the boundary version gets rid of that memory.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.