Simplest c++ solution, easy and clear, have a look


  • 6
    R

    comments will be highly appreciated .

    vector<vector<int>> generateMatrix(int n) {
            // 2d vector initialization  vector<vector<int>> myvec(rowsize,vector<int>(colsize,0));
            vector<vector<int>> res(n,vector<int>(n,0));
            if(!n) return res;
            
            int l=0,r=n-1,t=0,b=n-1,limit=n*n+1;  // l=left column , r=right column , t=top row, b=bottom row 
            int count=1;
            
            while(count<limit){         // loop until count == n*n 
                for(int i=l;i<=r;i++) res[t][i]=count++; // process top row
                t++;
                for(int i=t;i<=b;i++) res[i][r]=count++; // process right column
                r--;
                if(count==limit) break;         // termination condition to avoid overwritting          
                for(int i=r; i>=l;i--) res[b][i]=count++; // process bottom row
                b--;
                for(int i=b;i>=t;i--) res[i][l]=count++;  //process left column
                l++;
            }
            
           return res;
        }

  • 0
    L

    code simply explains very well .. thanks


  • 0
    L

    n * n could overflow...
    Change count == limit to t > b...


Log in to reply
 

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