#885

Spiral Matrix III

pupil · 450 · lc medium +26 · verified · 84.5% accepted · 1,662 likes · top 96%

Description

Starting at cell (rStart, cStart) of a rows x cols grid and initially facing east, walk outward in a clockwise spiral. Whenever the path leaves the grid boundary, continue walking outside and re-enter the grid when the path returns inside. Keep walking until all rows * cols cells have been visited.

Return the coordinates of every grid cell in the order they were visited.

Example 1:

Input: rows = 1, cols = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]

Example 2:

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

Code

1
2
3