class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        // 判断输入
        
        /* left right,low,high
            左->右
            left++到right,(left, low)
            右->左
            right--到left (right,low)
            上->下
            
        */
        vector<int>ret;
        if (matrix.size() == 0) {
            return ret;
        }
        
        int high = matrix.size() - 1;
        int right = matrix[0].size() - 1;
        int low = 0, left = 0;
        
        while (low <= high && left <= right) {
            // 向右的话,竖直反向是不变的,low++
            for(int i = left; i <= right; i++) {
                ret.push_back(matrix[low][i]);
            }
            // 向下,列不变的
            for(int i = low + 1; i <= high; i++) {
                ret.push_back(matrix[i][right]);
            }
            // 向左
            if (low < high) {
                for (int i = right - 1; i >= left; i--) {
                    ret.push_back(matrix[high][i]);
                }
            }
            // 向上,为了避免重复访问
            if (left < right) {
                for (int i = high - 1; i >= low + 1; i--) {
                    ret.push_back(matrix[i][left]);
                }
            }
            low ++;
            high--;
            left++;
            right--;
        }
         
        return ret;
    }
};