An Accept 0ms C++ solution, a little bit long but understandable


  • 0
    Y
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            vector<int> ans = {};
            if(matrix.size() == 0) return ans;
            int hLmt = matrix[0].size();
            int vLmt = matrix.size();
            int upb = 0, lowb = vLmt -1;
            int leftb = 0, rightb = hLmt - 1;
            bool right = true, down = false, left = false, up = false;
            int n = 0, m = 0;
            while(ans.size() != hLmt*vLmt) {
                if(right) {
                    ans.push_back(matrix[m][n]);
                    n++;
                    if(n > rightb) {
                        right = false;
                        down = true;
                        left = false;
                        up = false;
                        n--;
                        m++;
                        upb++;
                    }
                    continue;
                }
                if(down) {
                    ans.push_back(matrix[m][n]);
                    m++;
                    if(m > lowb) {
                        right = false;
                        down = false;
                        left = true;
                        up = false;
                        m--;
                        n--;
                        rightb--;
                    }
                    continue;
                }
                if(left) {
                    ans.push_back(matrix[m][n]);
                    n--;
                    if(n < leftb) {
                        right = false;
                        down = false;
                        left = false;
                        up = true;
                        n++;
                        m--;
                        lowb--;
                    }
                    continue;
                }
                if(up) {
                    ans.push_back(matrix[m][n]);
                    m--;
                    if(m < upb) {
                        right = true;
                        down = false;
                        left = false;
                        up = false;
                        m++;
                        n++;
                        leftb++;
                    }
                    continue;
                }
            }
            return ans;
        }
    };

Log in to reply
 

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