← Home

59. Spiral Matrix II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
59

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 59. Spiral Matrix II, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. 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: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • time: O(N^2), space: O(1)

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. 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 code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • 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. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

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^2), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Spiral Matrix II.
02//Memory Usage: 6.8 MB, less than 8.22% of C++ online submissions for Spiral Matrix II.
03//time: O(N^2), space: O(1)
04class Solution {
05public:
06    vector<vector<int>> generateMatrix(int n) {
07        vector<vector<int>> ans(n, vector<int>(n, 0));
08        
09        int r1 = 0, r2 = n-1, c1 = 0, c2 = n-1;
10        
11        int k = 1;
12        while(r1 <= r2 && c1 <= c2){
13            for(int c = c1; c <= c2; ++c) ans[r1][c] = k++;
14            for(int r = r1+1; r <= r2; ++r) ans[r][c2] = k++;
15            if(r1 < r2 && c1 < c2){
16                for(int c = c2-1; c >= c1; --c) ans[r2][c] = k++;
17                for(int r = r2-1; r >= r1+1; --r) ans[r][c1] = k++;
18            }
19            
20            r1++;
21            r2--;
22            c1++;
23            c2--;
24        }
25        
26        return ans;
27    }
28};
29
30//Approach 2: Optimized spiral traversal
31//Runtime: 4 ms, faster than 16.12% of C++ online submissions for Spiral Matrix II.
32//Memory Usage: 6.8 MB, less than 9.17% of C++ online submissions for Spiral Matrix II.
33//time: O(N^2), space: O(1)
34class Solution {
35public:
36    vector<vector<int>> generateMatrix(int n) {
37        vector<vector<int>> ans(n, vector<int>(n, 0));
38        
39        vector<int> dirs = {0, 1, 0, -1, 0};
40        int dir = 0;
41        int r = 0, c = 0;
42        int k = 1;
43        
44        while(k <= n*n){
45            ans[r][c] = k++;
46            
47            if(ans[(r + n + dirs[dir])%n][(c + n + dirs[dir+1])%n] != 0){
48                dir = (dir+1) % 4;
49            }
50            
51            r += dirs[dir];
52            c += dirs[dir+1];
53        }
54        
55        return ans;
56    }
57};

Cost

Complexity

Time
O(N^2), space: O(1)
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.