15 lines simple c++ solution, easy to understand


  • 0
    T
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> ret;
            if (matrix.empty()) return ret;
            int m = matrix.size(), n = matrix[0].size();
            int u = 0, d = m-1, l = 0, r = n-1, x = 0, y = 0, tot = 0, limit = n*m;
            while (tot < limit) {
                while (tot<limit && y<=r) {ret.push_back(matrix[x][y++]); ++tot;}
                u++; y--; x++;
                while (tot<limit && x<=d) {ret.push_back(matrix[x++][y]); ++tot;}
                r--; x--; y--;
                while (tot<limit && y>=l) {ret.push_back(matrix[x][y--]); ++tot;}
                d--; y++; x--;
                while (tot<limit && x>=u) {ret.push_back(matrix[x--][y]); ++tot;}
                l++; x++; y++;
            }
            return ret;
        }
    };

Log in to reply
 

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