顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

思路:

就是按照题意顺时针访问,一次一圈。需要注意的是当只有一行或只有一列的情况,需要做好判断。

代码:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        if (m == 0) {
            return {};
        }
        int n = matrix[0].size();
        int top = 0,bottom = m-1,left = 0,right = n-1;
        vector<int> ans;
        while (top <= bottom && left <= right) {
            for(int i = left;i <= right;i++) {
                ans.emplace_back(matrix[top][i]);
            }
            top++;
            for(int i = top;i <= bottom;i++) {
                ans.emplace_back(matrix[i][right]);
            }
            right--;
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    ans.emplace_back(matrix[bottom][i]);
                }
            }
            bottom--;
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    ans.emplace_back(matrix[i][left]);
                }
                
            }
            left++;
        }
        return ans;
    }
};