Tuesday, October 28, 2014

Spiral Matrix

//first one, do it in a natural way

    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> ret;
       
        int row=matrix.size();
        if(row==0)
            return ret;
        int col=matrix[0].size();

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

No comments:

Post a Comment