Posted on

Description

Submission

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<vector<int>> dir{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        vector<int> res;
        if(matrix.empty()) return res;
        int padding = 0;
        int nDir = 0;
        int rowMax = matrix.size() - 1;
        int colMax = matrix[0].size() - 1;
        for(int i = 0, j = 0; true; ) {

            res.push_back(matrix[i][j]);

            if((dir[nDir][1] == 1 && j + padding == colMax) ||
               (dir[nDir][0] == 1 && i + padding == rowMax) ||
               (dir[nDir][1] == -1 && j == padding) ||
               (dir[nDir][0] == -1 && i == padding)) {

                nDir++;
                if(nDir == 3) padding++;
                if(nDir == 4) nDir = 0;
            }


            i += dir[nDir][0];
            j += dir[nDir][1];

            if((dir[nDir][1] == 1 && j + padding > colMax) ||
               (dir[nDir][0] == 1 && i + padding > rowMax) ||
               (dir[nDir][1] == -1 && j < padding) ||
               (dir[nDir][0] == -1 && i < padding)) {
                break;
            }
        }
        return res;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *