Accepted c++ solution 0 ms


  • 1
    H
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int> >& matrix) {
            vector<int> ans;
            int num_row = matrix.size();
            int num_col = num_row>0 ? matrix[0].size() : 0;
            int row_start = 0;
            int col_start = 0;
            while(num_row > 0 && num_col > 0) {
                for(int i=0; i<num_col; i++)
                    ans.push_back(matrix[row_start][i+col_start]);
                for(int i=1; i<num_row; i++)
                    ans.push_back(matrix[i+row_start][col_start+num_col-1]);
                for(int i=num_col-2; i>=0 && num_row > 1; i--)
                    ans.push_back(matrix[row_start+num_row-1][col_start+i]);
                for(int i=num_row-2; i>=1 && num_col > 1; i--)
                    ans.push_back(matrix[i+row_start][col_start]);
                num_col -= 2;
                num_row -= 2;
                row_start++;
                col_start++;
            }
            return ans; 
        }
    };

Log in to reply
 

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