Tuesday, October 28, 2014

Spiral Matrix II

 //similar to Spiral Matrix
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int>> matrix(n,vector<int>(n,0));
       
        int row=n,col=n;

        int rowStart=0,colStart=0;
        int v=1;
        while(row>0&&col>0)
        {
           
            for(int k=colStart;k<colStart+col;k++)
                matrix[rowStart][k]=v++;
            if(row>2)   
                for(int k=rowStart+1;k<rowStart+row-1;k++)
                    matrix[k][colStart+col-1]=v++;
            if(row>1)       
              for(int k=colStart+col-1;k>=colStart;k--)
                  matrix[rowStart+row-1][k]=v++;
            if(row>2&&col>1)    
                for(int k=rowStart+row-2;k>=rowStart+1;k--)
                    matrix[k][colStart]=v++;
            row-=2;col-=2;
            rowStart++; colStart++;
        }
        return matrix;
    }

No comments:

Post a Comment