4ms C++ with comments, any advice welcomes!


  • 0
    S
    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector< vector<int> > matrix(n,vector<int>(n,0));
            if(n==0)
            return matrix;
            int left=0,right=n-1;
            int top=0,down=n-1;
            int count=1;
            while(true){
                //fill from left to right
                for(int i=left;i<=right;++i)
               {
                   matrix[top][i]=count;
                   count++;
               }
               top++;
               if(top>down)
               break;
    //fill from top to down
               for(int j=top;j<=down;++j){
                   matrix[j][right]=count;
                   count++;
               }
               right--;
               if(right<left)
               break;
               //fill from right to left
               for(int k=right;k>=left;--k){
                   matrix[down][k]=count;
                   count++;
               }
               down--;
               if(down<top)
               break;
               //fill from down to top
               for(int l=down;l>=top;--l){
                   matrix[l][left]=count;
                   count++;
               }
               left++;//left column is finished
               if(left>right)
               break;
            }
            return matrix;
            
        }
    };`enter code here`

Log in to reply
 

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