C++ Solution with bound


  • 0
    B
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> result;
            if(matrix.size()==0)return result;
            int m = matrix.size(), n = matrix[0].size();
            int r1=0, r2=m-1, c1=0, c2= n-1;
            while(true){
                for(int i=c1;i<=c2;i++)result.push_back(matrix[r1][i]);r1++;
                if(r1>r2)break;
                for(int i=r1;i<=r2;i++)result.push_back(matrix[i][c2]);c2--;
                if(c1>c2)break;
                for(int i=c2;i>=c1;i--)result.push_back(matrix[r2][i]);r2--;
                if(r1>r2)break;
                for(int i=r2;i>=r1;i--)result.push_back(matrix[i][c1]);c1++;
                if(c1>c2)break;
            }
            return result;
       
    

Log in to reply
 

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