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

Walking Robot Simulation Problem

LeetCode 874. A robot on an infinite XY-plane starts at...

Valid Mountain Array Problem

LeetCode 941. Given an array of integers arr, return true...

Sum Of Even Numbers After Queries Problem

LeetCode 985. You are given an integer array nums and...

Partition Array Into Disjoint Intervals Problem

LeetCode 915. Given an integer array nums, partition it into...

Monotonic Array Problem

LeetCode 896. An array is monotonic if it is either...

Maximize Distance To Closest Person Problem

LeetCode 849. You are given an array representing a row...