54. Spiral Matrix

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix)
    {
        int up = 0, down = matrix.size() - 1;
        int left = 0, right = matrix[0].size() - 1;
        vector<int> res;
        int direction = 0;

        while (true)
        {
            if (direction == 0)
            {
                for (int i = left; i <= right; ++i)
                {
                    res.push_back(matrix[up][i]);
                }
                ++up;
            }
            else if (direction == 1)
            {
                for (int i = up; i <= down; ++i)
                {
                    res.push_back(matrix[i][right]);
                }
                --right;
            }
            else if (direction == 2)
            {
                for(int i = right; i >= left; i--)
                {
                    res.push_back(matrix[down][i]);
                }
                --down;
            }
            else {
                for(int i = down; i >= up; i--)
                {
                    res.push_back(matrix[i][left]);
                }
                ++left;
            }

            if (up > down || left > right) break;
            direction = (direction + 1) % 4;
        }
        return res;
    }
};
  • T: O(MN˙)O(M \dot N)
  • S: O(MN˙)O(M \dot N)