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

题目描述

在这里插入图片描述

思路分析

在这里插入图片描述

代码展示

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
         if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};
        }
        vector<int> ret;
        int left = 0;
        int right = matrix[0].size() - 1;
        int top = 0;
        int botten = matrix.size() - 1;
        int col = 0;
        int row = 0;
        while (left <= right && top <= botten) {
            for (col = left; col <= right; col++) {
                ret.push_back(matrix[top][col]);
            }
            for (row = top+1; row <= botten; row++) {
                ret.push_back(matrix[row][right]);
            }
            if (left < right && top < botten) {
                for (col = right - 1; col >= left; col--) {
                    ret.push_back(matrix[botten][col]);
                }
                for (row = botten - 1; row > top; row--) {
                    ret.push_back(matrix[row][left]);
                }
            }
            top++;
            botten--;
            left++;
            right--;
        }
        return ret;
    }
};

结果分析

在这里插入图片描述

时间复杂度O(mn)
空间复杂度O(1)

猜你喜欢

转载自blog.csdn.net/ifwecande/article/details/107874298