Concise solution with c++


  • 0
    X
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& m) {
            vector<int> ret;
            
            if (m.size() == 0) return ret;
            
            int l = 0, t = 0, b = m.size()-1,  r = m[0].size()-1;
            int total = (b+1) * (r+1);
            int i = 0, j = 0;
            
            while (total > 0) {
                while (j <= r && total > 0) {ret.push_back(m[i][j]); j++; total--;}
                i++; t++;j--;
                while (i <= b && total > 0) {ret.push_back(m[i][j]); i++; total--;}
                j--; r--;i--;
                while (j >= l && total > 0) {ret.push_back(m[i][j]); j--; total--;}
                i--; b--;j++;
                while (i >= t && total > 0) {ret.push_back(m[i][j]); i--; total--;}
                j++; l++;i++;
            }
            
            return ret;
        }
    };

Log in to reply
 

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