59. Spiral Matrix II

 59Spiral Matrix II

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

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 1 <= n <= 20

The solution to the above question is


class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>>v(n,vector<int>(n,-1));
        int SR=0,ER=v.size()-1;
        int SC=0, EC=v[0].size()-1;
        int count=1;
        int a=n*n;
        // cout<<a;
        vector<int>ans;
        while(SR<=ER && SC<=EC){
            for(int i=SC; i<=EC; i++){
                // ans.push_back(v[SR][i]);
                v[SR][i]=(count);
                count++;
                if(count>a){
                return v;
            }
            }
            SR++;
            
            for(int i=SR;i<=ER; i++){
               (v[i][EC]=count);
                count++;
                if(count>a){
                return v;
            }
            }
            EC--;
            
            for(int i=EC; i>=SC; i--){
               (v[ER][i])=count;
                count++;
                if(count>a){
                return v;
            }
            }
            ER--;
            
            for(int i=ER; i>=SR; i--){
                (v[i][SC])=count;
                count++;
                if(count>a){
                return v;
            }
            }
            SC++;
            
        }
        return v;
    }
};

Post a Comment

0 Comments