c++ with example explanation 6ms


  • 0

    /*

    *There are 2 cases n is odd/even

    • in each iteration we will fill a single spiral loop
      Ex:
      In case n is 4
      in the first iter we will fill

    1 2 3 4
    5 x x 8
    9 x x 12
    13 14 15 16

    In the next we will fill the x's

    In case n is odd Ex: n is 3
    after iteration in the loop the centre element will be left out.
    1 2 3
    4 x 6
    7 8 9

    so we will fill that in the end.
    the first for loop is for top row,
    2nd is for last col,
    3rd is for bottom row,
    4th is for first col in each iteration

    */

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) 
        {
            int num = 1,start=0,iter=n;
            int sq = n*n;
            vector<vector<int>> mat(n,vector<int>(n,0));
            
            while(num < sq)    
            {
                for(int i=start;i<iter-1;i++)
                    mat[start][i] = num++;
                
                for(int i=start;i<iter-1;i++)
                    mat[i][iter-1] = num++;    
            
                for(int i=iter-1;i>start;i--)
                    mat[iter-1][i] = num++;
            
                for(int i=iter-1;i>start;i--)
                    mat[i][start] = num++;
            
                start++;iter--; 
            }
            
            if(n%2)
                mat[n/2][n/2] = sq;
            
            return mat;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.