力扣 54. 螺旋矩阵

🔗 https://leetcode.cn/problems/spiral-matrix

题目

  • 给一个矩阵,按照顺时针螺旋式顺序进行遍历

思路

  • 模拟
  • 下标先碰到某 col 变方向, 再碰到某 row 变方向,以此交替,碰到 col 和 row 的先后顺序可以初始化定义出来
  • 右、下、左、上,四个方向是依次变化
  • 若某元素再次碰到,或者 index 出界,则表示遍历完,返回答案

代码

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int row = matrix.size(), col = matrix[0].size();
        vector<int> col_border(col + 4), row_border(row + 4);
        for (int i = 0; i <= (col / 2 + 1); i++) {
            col_border[i * 2] = col - i - 1;
            col_border[i*2 + 1] = i;
        }
        for (int i = 0; i <= (row /2 +1); i++) {
            row_border[i * 2] = row - i - 1;
            row_border[i*2 + 1] = i + 1;
        }
        vector<vector<bool>> m(row, vector<bool>(col));
        int x, y, d, step;
        x = y = d = step = 0;
        vector<int> ans;
        vector<vector<int>> dir = {{0,1}, {1, 0}, {0, -1}, {-1, 0}};
        while (true) {
            while (y != col_border[step]) {
                ans.push_back(matrix[x][y]);
                m[x][y] = true;
                x += dir[d][0], y += dir[d][1];
            }
            ans.push_back(matrix[x][y]);
            m[x][y] = true;
            d = (d+1) % 4;
            x += dir[d][0], y += dir[d][1];
            if (x >= row || x < 0) return ans;
            if (m[x][y]) return ans;
            while (x != row_border[step]) {
                ans.push_back(matrix[x][y]);
                m[x][y] = true;
                x += dir[d][0], y += dir[d][1];
            }
            ans.push_back(matrix[x][y]);
            m[x][y] = true;
            d = (d+1) % 4;
            x += dir[d][0], y += dir[d][1];
            if (y >= col || y < 0) return ans;
            if (m[x][y]) return ans;
            step++;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值