剑指 Offer 29 顺时针打印矩阵

标签: 剑指 Offer 发布于:2022-02-23 17:11:09 编辑于:2022-02-25 20:39:33 浏览量:859

概述

https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

https://leetcode.com/problems/spiral-matrix/

解法

注意:

  1. top_bound = 1;
  2. while 里需要是 >= 或 <=,然后我们再手动移位,不然会出现无法正常调整方向的问题。
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ans;
        if (matrix.size() == 0) return ans;
        int lb = 0;
        int rb = matrix[0].size() - 1;
        int tb = 1;
        int bb = matrix.size() - 1;
        int i = 0, j = 0;
        int d = 0;
        int count = matrix.size() * matrix[0].size();
        while (count > 0) {
            d %= 4;
            if (d == 0) {
                while (j <= rb) {
                    ans.push_back(matrix[i][j]);
                    j ++;
                    count --;
                }
                j --;
                i ++;
                rb --;
            } else if (d == 1) {
                while (i <= bb) {
                    ans.push_back(matrix[i][j]);
                    i ++;
                    count --;
                }
                i --;
                j --;
                bb --;
            } else if (d == 2) {
                while (j >= lb) {
                    ans.push_back(matrix[i][j]);
                    j --;
                    count --;
                }
                j ++;
                i --;
                lb ++;
            } else {
                while (i >= tb) {
                    ans.push_back(matrix[i][j]);
                    i --;
                    count --;
                }
                i ++;
                j ++;
                tb ++;
            }
            d ++;
        }
        return ans;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/