Spiral Matrix II Problem


Description

LeetCode Problem 59.

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

1
2
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

1
2
Input: n = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 20


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > ret( n, vector<int>(n) );
        int k = 1, i = 0;
        while( k <= n * n )
        {
            int j = i;
            // four steps
            while( j < n - i ) 
                // 1. horizonal, left to right
                ret[i][j++] = k++;
            j = i + 1;
            while( j < n - i ) 
                // 2. vertical, top to bottom
                ret[j++][n-i-1] = k++;
            j = n - i - 2;
            while( j > i ) 
                // 3. horizonal, right to left 
                ret[n-i-1][j--] = k++;
            j = n - i - 1;
            while( j > i ) 
                // 4. vertical, bottom to  top 
                ret[j--][i] = k++;
            // next loop
            i++; 
        }
        return ret;
    }
};




Related Posts

Plus One Problem

LeetCode 66. You are given a large integer represented as...

Spiral Matrix Problem

LeetCode 54. Given an m x n matrix, return all...

Spiral Matrix II Problem

LeetCode 59. Given a positive integer n, generate an n...

Jump Game Problem

LeetCode 55. Given an m x n matrix, return all...

Insert Interval Problem

LeetCode 57. Insert newInterval into intervals such that intervals is...