Spiral Matrix III

You start at the cell (rStart, cStart) of a rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, continue walking outside the grid, but you may return to the grid boundary later. Eventually, you will reach all rows * cols spaces of the grid.

Return an array of coordinates representing the positions of the grid in the order you visited them.

Example 1
Inputrows = 1, cols = 4, rStart = 0, cStart = 0
Output[[0,0],[0,1],[0,2],[0,3]]
Starting at (0, 0) and moving east visits the only row from left to right.
Example 2
Inputrows = 5, cols = 6, rStart = 1, cStart = 4
Output[[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
The coordinates are listed in the order they are reached by the clockwise spiral walk, ignoring positions while the walk is outside the grid.

Constraints

  • 1 <= rows, cols <= 100
  • 0 <= rStart < rows
  • 0 <= cStart < cols

Asked at 8 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate