Spiral Matrix III (LeetCode 885): Solution and Explanation
Start on a given cell of a rows x cols grid facing east and walk a clockwise spiral that keeps growing, even outside the grid. Return the coordinates of every grid cell in the order the walk first reaches it.
Intuition
Unlike the classic spiral problems, the walk here does not hug the grid border. It starts somewhere in the middle and grows outward, so parts of the spiral fall outside the grid.
Trying to clip the spiral to the grid leads to messy boundary logic. It is much easier to pretend the plane is infinite: walk the spiral exactly as drawn, and only write down positions that land inside the grid.
A square spiral has a simple rhythm. Leg lengths go 1, 1, 2, 2, 3, 3, ..., and you turn clockwise after every leg. So the whole walk is two nested loops: a growing step, two legs per step, and step moves per leg.
The walk stops as soon as all rows * cols cells are recorded. Each grid cell is reached exactly once, because the spiral never crosses itself.
Approach: Simulate the spiral on an infinite plane
- Set
dirs = [(0,1), (1,0), (0,-1), (-1,0)]for east, south, west, north and startresultwith[rStart, cStart]. - Set
r, c = rStart, cStart,step = 1andd = 0(facing east). - While
resulthas fewer thanrows * colscells: walk two legs. For each leg, movesteptimes in directiond, appending[r, c]whenever it is inside the grid, then turn withd = (d + 1) % 4. - After the two legs, increase
stepby one. Returnresult.
Step-by-step example
rows = 1, cols = 4, rStart = 0, cStart = 0
- Record (0,0). Step length 1: east to (0,1), recorded. South to (1,1), outside.
- Step length 2: west to (1,0) and (1,-1), north to (0,-1) and (-1,-1). All outside.
- Step length 3: east along row -1 to (-1,2), outside. Then south to (0,2), recorded, followed by (1,2) and (2,2), outside.
- Step lengths 4 and 5 circle further out, and the length-5 south leg passes (0,3), the last cell.
- The result has all 4 cells: [[0,0],[0,1],[0,2],[0,3]].
Code: Python, Java, C++
1class Solution:
2 def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
3 dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
4 result = [[rStart, cStart]]
5 r, c, step, d = rStart, cStart, 1, 0
6 while len(result) < rows * cols:
7 for _ in range(2):
8 dr, dc = dirs[d]
9 for _ in range(step):
10 r += dr
11 c += dc
12 if 0 <= r < rows and 0 <= c < cols:
13 result.append([r, c])
14 d = (d + 1) % 4
15 step += 1
16 return result1class Solution {
2 public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
3 int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
4 int[][] result = new int[rows * cols][];
5 result[0] = new int[]{rStart, cStart};
6 int k = 1, r = rStart, c = cStart, step = 1, d = 0;
7 while (k < rows * cols) {
8 for (int t = 0; t < 2; t++) {
9 for (int i = 0; i < step; i++) {
10 r += dirs[d][0];
11 c += dirs[d][1];
12 if (r >= 0 && r < rows && c >= 0 && c < cols) {
13 result[k++] = new int[]{r, c};
14 }
15 }
16 d = (d + 1) % 4;
17 }
18 step++;
19 }
20 return result;
21 }
22}1class Solution {
2public:
3 vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
4 int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
5 vector<vector<int>> result = {{rStart, cStart}};
6 int r = rStart, c = cStart, step = 1, d = 0;
7 while ((int)result.size() < rows * cols) {
8 for (int t = 0; t < 2; t++) {
9 for (int i = 0; i < step; i++) {
10 r += dirs[d][0];
11 c += dirs[d][1];
12 if (r >= 0 && r < rows && c >= 0 && c < cols) {
13 result.push_back({r, c});
14 }
15 }
16 d = (d + 1) % 4;
17 }
18 step++;
19 }
20 return result;
21 }
22};Time and space complexity
O(max(rows, cols)^2)
The spiral has to grow until it covers the grid from the start cell, so its side length is at most about 2 * max(rows, cols), and the walk visits that many squared positions in total.
O(1)
Besides the output list of rows * cols coordinates, only the position, direction and step length are stored.
Other approaches
Sort by ring and angle (time O(rows * cols * log(rows * cols)), space O(rows * cols))
Each cell's visit time is determined by its Chebyshev distance from the start (which ring it is on) and its position along that ring. You can compute a key per cell and sort, but getting the ring order exactly right is fiddly.
Skip outside stretches (time O(rows * cols + max(rows, cols)), space O(1))
When a whole leg lies outside the grid you can jump to its end in one move instead of stepping through it. This saves time on far-off legs but adds clipping logic for little benefit at these sizes.
Common mistakes
- Stopping the walk when it leaves the grid. The spiral must keep going outside so it can come back in on a later leg.
- Increasing the leg length after every leg instead of after every second leg, which produces a skewed spiral that skips cells.
- Forgetting to record the start cell before the first move.
- Turning counterclockwise. The order is east, south, west, north.
Frequently asked questions
Why are the leg lengths 1, 1, 2, 2, 3, 3?
After going east and south, you need to go one further west and north to wrap around the cells you already covered. Every two turns the square grows by one cell on each side.
Can a cell be visited twice?
No. The spiral never crosses itself, so every position on the plane, and therefore every grid cell, is reached at most once.
How far outside the grid can the walk go?
Up to about max(rows, cols) cells beyond the border, when the start is in a corner and the spiral has to grow to reach the opposite corner.
What is the time complexity of Spiral Matrix III?
O(max(rows, cols)^2) for the walk, which includes the steps taken outside the grid. The output itself has rows * cols entries.