Spiral Matrix III - Problem
You start at cell (rStart, cStart) of an rows × 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, we continue our walk outside the grid (but may return to the grid boundary later).
Eventually, we 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.
Input & Output
Example 1 — Small 2×2 Grid
$
Input:
rows = 1, cols = 4, rStart = 0, cStart = 0
›
Output:
[[0,0],[0,1],[0,2],[0,3]]
💡 Note:
Start at (0,0), walk east: (0,0)→(0,1)→(0,2)→(0,3). All positions are in-bounds and visited in spiral order.
Example 2 — Square Grid Starting Center
$
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]]
💡 Note:
Start at (1,4), spiral outward: 1 east, 1 south, 2 west, 2 north, 3 east, etc. Only record positions within the 5×6 grid bounds.
Example 3 — Single Cell Grid
$
Input:
rows = 1, cols = 1, rStart = 0, cStart = 0
›
Output:
[[0,0]]
💡 Note:
Edge case: only one cell exists, so return that single position.
Constraints
- 1 ≤ rows, cols ≤ 100
- 0 ≤ rStart < rows
- 0 ≤ cStart < cols
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
rows=1, cols=4, start at (0,0)
2
Spiral Walk
Walk east: (0,0)→(0,1)→(0,2)→(0,3)
3
Result Array
Return coordinates in visit order: [[0,0],[0,1],[0,2],[0,3]]
Key Takeaway
🎯 Key Insight: Simulate clockwise spiral with increasing step pattern (1,1,2,2,3,3...) and record only in-bounds positions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code