2ms using C++ to solve the problem


  • 0
    B

    class Solution {
    public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {

        vector<int> output;
        
        if (matrix.size() == 0) return output;
    
        int sizeRow = matrix.size();
        
        int sizeColumn = matrix[0].size();
        
        int startRow = 0,startColumn = 0;
        
        while(sizeRow>0 && sizeColumn>0){
            
            for (int i = 0;i<sizeColumn || i == 0;++i)
                output.push_back(matrix[startRow][i+startColumn]);
                
            for (int i = 1;i<sizeRow;++i)
                output.push_back(matrix[startRow+i][startColumn+sizeColumn-1]);
                
            for (int i = sizeColumn-2;i>=0 && sizeRow > 1 && sizeColumn > 1;--i)
                output.push_back(matrix[startRow+sizeRow-1][startColumn+i]);
                
            for (int i = sizeRow-2;i>0 && sizeRow > 1 && sizeColumn > 1;--i)
                output.push_back(matrix[startRow+i][startColumn]);
                
            startRow++;
            startColumn++;
            
            sizeRow-=2;
            sizeColumn-=2;
        }
        
        return output;
    }
    

    };


Log in to reply
 

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