← Home

885. Spiral Matrix III

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
885

Let's make this one less mysterious. For 885. Spiral Matrix III, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The solution is organized around the main LeetCode entry point and a few local helpers.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east.
03
04Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the grid is at the last row and column.
05
06Now, we walk in a clockwise spiral shape to visit every position in this grid. 
07
08Whenever we would move outside the boundary of the grid, we continue our walk outside the grid (but may return to the grid boundary later.) 
09
10Eventually, we reach all R * C spaces of the grid.
11
12Return a list of coordinates representing the positions of the grid in the order they were visited.
13
14Example 1:
15
16Input: R = 1, C = 4, r0 = 0, c0 = 0
17Output: [[0,0],[0,1],[0,2],[0,3]]
18
19Example 2:
20
21Input: R = 5, C = 6, r0 = 1, c0 = 4
22Output: [[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]]
23
24Note:
25
261 <= R <= 100
271 <= C <= 100
280 <= r0 < R
290 <= c0 < C
30**/
31
32//Runtime: 64 ms, faster than 48.33% of C++ online submissions for Spiral Matrix III.
33class Solution {
34public:
35    vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {
36        vector<vector<int>> ans;
37        vector<int> cur;
38        cur.push_back(r0); cur.push_back(c0);
39        
40        int times = 1;
41        
42        int rdstride = 2*times-1; //right, down
43        int lustride =  2*times; //left, up
44        
45        char dir = 'r';
46        int res = rdstride;
47        
48        while(ans.size()!=R*C){
49            //only record that are inside the boundary
50            if(cur[0]>=0 && cur[0]<R && cur[1]>=0 && cur[1]<C){
51                ans.push_back(cur);
52            }
53            
54            //go to next position
55            //(and select the next direction, res)
56            switch(dir){
57                case 'r':
58                    cur[1]+=1;
59                    res--;
60                    if(res==0){
61                        dir = 'd';
62                        res = rdstride;
63                    }
64                    break;
65                case 'd':
66                    cur[0]+=1;
67                    res--;
68                    if(res==0){
69                        dir = 'l';
70                        res = lustride;
71                    }
72                    break;
73                case 'l':
74                    cur[1]-=1;
75                    res--;
76                    if(res==0){
77                        dir = 'u';
78                        res = lustride;
79                    }
80                    break;
81                case 'u':
82                    cur[0]-=1;
83                    res--;
84                    if(res==0){
85                        dir = 'r';
86                        times+=1;
87                        rdstride = 2*times-1;
88                        lustride =  2*times;
89                        res = rdstride;
90                    }
91            }
92            
93        }
94        return ans;
95    }
96};
97
98/**
99Approach 1: Walk in a Spiral
100Intuition
101
102We can walk in a spiral shape from the starting square, ignoring whether we stay in the grid or not. 
103Eventually, we must have reached every square in the grid.
104
105Algorithm
106
107Examining the lengths of our walk in each direction, we find the following pattern: 1, 1, 2, 2, 3, 3, 4, 4, ... 
108That is, we walk 1 unit east, then 1 unit south, then 2 units west, then 2 units north, then 3 units east, etc. 
109Because our walk is self-similar, this pattern repeats in the way we expect.
110
111After, the algorithm is straightforward: perform the walk and record positions of the grid in the order we visit them. 
112Please read the inline comments for more details.
113
114//Java
115class Solution {
116    public int[][] spiralMatrixIII(int R, int C, int r0, int c0) {
117        int[] dr = new int[]{0, 1, 0, -1};
118        int[] dc = new int[]{1, 0, -1, 0};
119
120        int[][] ans = new int[R*C][2];
121        int t = 0;
122
123        ans[t++] = new int[]{r0, c0};
124        if (R * C == 1) return ans;
125
126        for (int k = 1; k < 2*(R+C); k += 2)
127            for (int i = 0; i < 4; ++i) {  // i: direction index
128                int dk = k + (i / 2);  // number of steps in this direction
129                for (int j = 0; j < dk; ++j) {  // for each step in this direction...
130                    // step in the i-th direction
131                    r0 += dr[i];
132                    c0 += dc[i];
133                    if (0 <= r0 && r0 < R && 0 <= c0 && c0 < C) {
134                        ans[t++] = new int[]{r0, c0};
135                        if (t == R * C) return ans;
136                    }
137                }
138            }
139
140        throw null;
141    }
142}
143
144Complexity Analysis
145
146Time Complexity: O((max(R,C))^2). 
147Potentially, our walk needs to spiral until we move RR in one direction, and CC in another direction, 
148so as to reach every cell of the grid.
149
150Space Complexity: O(R∗C), the space used by the answer. 
151**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.