其他分享
首页 > 其他分享> > 剑指Offer #29 顺时针打印矩阵

剑指Offer #29 顺时针打印矩阵

作者:互联网

在这里插入图片描述
注意矩阵为空的情况。

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

标签:顺时针,matrix,Offer,int,res,29,up,right,left
来源: https://blog.csdn.net/m0_51509503/article/details/121873410