Leetcode|固定四角从外围至内围|54. 螺旋矩阵

2022-01-10 15:18:08 浏览数 (1)

1 模拟

代码语言:javascript复制
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        int rowlen = matrix.size();      // 行数
        int collen = matrix[0].size();   // 列数
        int left = 0, right = collen - 1, up = 0, down = rowlen - 1;              // 左右上下边界,从外围至内围
        while (left < right && up < down) {  // 注意是小于号<
            for (int i = left; i < right; i  ) res.emplace_back(matrix[up][i]);   // (上)左->(上)右
            for (int i = up; i < down; i  ) res.emplace_back(matrix[i][right]);   // (右)上->(右)下
            for (int i = right; i > left; i--) res.emplace_back(matrix[down][i]); // (下)右->(下)左
            for (int i = down; i > up; i--) res.emplace_back(matrix[i][left]);    // (左)下->(左)上
            // 四个边界同时收紧
            left  ; right--; up  ; down--;
        }
        if (left == right)   // 剩余最后一列
            for (int i = up; i <= down; i  ) res.emplace_back(matrix[i][left]);
        else if (up == down) // 剩余最后一行
            for (int i = left; i <= right; i  ) res.emplace_back(matrix[up][i]);
        return res;
    }
};

0 人点赞