LeetCode 54. 螺旋矩阵

2022-01-13 14:42:07 浏览数 (1)

题目

思路

代码语言:javascript复制
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        int num, n = 0;
        int i = 0, j = 0;
        int left = 0, right = matrix[0].size(), up = 1, down = matrix.size();
        num = matrix.size() * matrix[0].size();
        while (n < num) {
            while (j < right) {
                res.push_back(matrix[i][j]);
                j  ;
                n  ;
            }
            if (n >= num) return res;
            right--;
            j--;
            i  ;
            while (i < down) {
                res.push_back(matrix[i][j]);
                i  ;
                n  ;
            }
            if (n >= num) return res;
            down--;
            i--;
            j--;
            while (j >= left) {
                res.push_back(matrix[i][j]);
                j--;
                n  ;
            }
            if (n >= num) return res;
            left  ;
            j  ;
            i--;
            while (i >= up) {
                res.push_back(matrix[i][j]);
                i--;
                n  ;
            }
            if (n >= num) return res;
            up  ;
            i  ;
            j  ;
        }
        return res;
    }
};
ode

0 人点赞