C++ Very Concise No Condition Check Solution 0ms


  • 1
    Y

    Explanations to be added later.

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            if (!matrix.size()) return vector<int>{};
            vector<int> result;
            int dir = 0;
            int steps[2] = {matrix.size(), matrix[0].size()};
            int posNeg[2] = {1, -1};
            int fb[2] = {0, 0};
            int loc[2] = {0, -1};
    
            while (true)
            {
                for (int i = 0; i < steps[dir^1]; i++)
                {
                    loc[dir^1] += posNeg[fb[dir]];
                    result.push_back(matrix[loc[0]][loc[1]]);
                }
                if (--steps[dir] == 0) break;
                fb[dir] ^= 1;
                dir ^= 1;
            }
            return result;
        }
    };

Log in to reply
 

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