螺旋矩阵

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
      if (matrix.empty()) {
        return std::vector<int>();
      }
      
      std::vector<int> res;
      
      int left = 0, right = matrix[0].size() - 1, up = 0, down = matrix.size() - 1;
      
      while (left <= right && up <= down) {
        for (int i = left; i <= right; ++i) {
          res.push_back(matrix[up][i]);
        }
        ++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 i = right; i >= left; --i) {
          res.push_back(matrix[down][i]);
        }
        --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;
    }
};