⭐️⭐️

# 題目敘述

Given an m x n matrix , return all elements of the matrix in spiral order.

# Example 1

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

# Example 2

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

# Solution

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        int m = matrix.size()-1;
        int n = matrix[0].size()-1;
        int left = 0, right = n, up = 0, down = m;
        while (left <= right && up <= down) {
            for (int j=left; j<=right; j++) res.push_back(matrix[up][j]);
            up++;
            if (up > down) break;
            for (int i=up; i<=down; i++) res.push_back(matrix[i][right]);
            right--;
            if (left > right) break;
            for (int j=right; j>=left; j--) res.push_back(matrix[down][j]);
            down--;
            if (up > down) break;
            for (int i=down; i>=up; i--) res.push_back(matrix[i][left]);
            left++;  
            if (left > right) break;
        }
        return res;
    }
};