由于行列不相等,因此定义四个变量用于记录边界:

  • 左边界left
  • 右边界right
  • 上边界top
  • 下边界bottom

然后以top和left基准层层打印,值得注意的是,为了避免重复打印,我们需要在打印下边和左边时额外判断一下top和bottom以及left和right是否相等:

//
// Created by jt on 2020/9/29.
//
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> res;
        if (matrix.empty()) return res;
        int top = 0, bottom = matrix.size() - 1;
        int left = 0, right = matrix[0].size() - 1;
        while (top < (matrix.size()+1) / 2 && left < (matrix[0].size()+1) / 2) {
            // 上
            for (int i = left; i <= right; ++i) {
                res.push_back(matrix[top][i]);
            }
            // 右
            for (int i = top + 1; i <= bottom; ++i) {
                res.push_back(matrix[i][right]);
            }
            // 下,注意这里的top!=bottom
            for (int i = right - 1; top != bottom && i >= left; --i) {
                res.push_back(matrix[bottom][i]);
            }
            // 左,注意这里的left!=right
            for (int i = bottom - 1; left != right && i >= top + 1; --i) {
                res.push_back(matrix[i][left]);
            }
            ++top, --bottom, ++left, --right;
        }
        return res;
    }
};