Spiral Matrix III

Medium Topics Company Tags

Start at [rStart, cStart] in a grid with rows rows and cols columns. Coordinates are zero-based; moving east increases the column and moving south increases the row.

Walk in a clockwise spiral: east 1 step, south 1 step, west 2 steps, north 2 steps, east 3 steps, south 3 steps, and so on. Increase the segment length after every two turns.

Continue the same spiral even when it leaves the grid. Record the starting cell and every in-bounds cell as you visit it; do not record positions outside the grid. Return all rows × cols coordinates in visitation order.

Numbers in the diagrams show the visit order, starting from 1. Gaps between arrows represent travel outside the grid.

Example 1:

Spiral Matrix III, example 1: illustration of the example

Input: rows = 2
cols = 2
rStart = 0
cStart = 0

Output: [[0,0],[0,1],[1,1],[1,0]]

Explanation: Record the starting cell [0,0], then move east to [0,1] and south to [1,1]. The next westward segment reaches [1,0], completing the grid.

Example 2:

Spiral Matrix III, example 2: illustration of the example

Input: rows = 1
cols = 3
rStart = 0
cStart = 1

Output: [[0,1],[0,2],[0,0]]

Explanation: Record [0,1] and then [0,2]. The spiral continues outside the one-row grid before reaching [0,0], which is the last remaining cell.

Example 3:

Spiral Matrix III, example 3: illustration of the example

Input: rows = 3
cols = 1
rStart = 1
cStart = 0

Output: [[1,0],[2,0],[0,0]]

Explanation: Record [1,0]. The spiral first returns to the column at [2,0], then later reaches [0,0]. Out-of-bounds steps are omitted.

Constraints:

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


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.