力扣54. 螺旋矩阵

文章描述了一种算法,通过模拟螺旋方向(右、下、左、上)遍历二维矩阵,同时维护已访问位置,以O(mn)的空间复杂度求解矩阵的螺旋顺序。作者还提出了优化空间复杂度到O(1)的可能性。
摘要由CSDN通过智能技术生成

模拟

  • 思路:
    • 转向表示:使用行下标和列下标变化;
      • 比如向上:行下标 - 1, 列下标,即 {-1, 0}
      • 同理向下 {1, 0}
      • {0, 1} 表示向右
      • {0, -1} 表示向左
    • 螺旋方向为:向右、向下、向左、向上,周期变化;
      • 从 4 个转向中周期选取

      • directIdx = (directIdx + 1) % 4;

    • 出现转向是 next 到达“边界”:
      • 真正的边界;
      • 已经访问过的成为了边界;
    • 预测下一个行列下标:
      • int nextRow = r + directions[directIdx][0];

      • int nextColumn = c + directions[directIdx][1];

    • 根据转向规则,更新行列下标:
      • r += directions[directIdx][0];

      • c += directions[directIdx][1];

    • 完整代码:
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int row = matrix.size();
        if (row == 0) {
            return {};
        }
        int column = matrix[0].size();
        if (column == 0) {
            return {};
        }

        std::vector<std::vector<bool>> visited(row, std::vector<bool>(column));
        int sz = row * column;
        std::vector<int> order(sz);

        int r = 0;
        int c = 0;
        int directIdx = 0;
        for (int i = 0; i < sz; ++i) {
            order[i] = matrix[r][c];
            visited[r][c] = true;
            int nextRow = r + directions[directIdx][0];
            int nextColumn = c + directions[directIdx][1];

            if (nextRow < 0 || nextRow >= row || 
                nextColumn < 0 || nextColumn >= column ||
                visited[nextRow][nextColumn]) {
                directIdx = (directIdx + 1) % 4;
            }

            r += directions[directIdx][0];
            c += directions[directIdx][1];
        }

        return order;
    }

private:
    static constexpr int directions[4][2] = {
        // right
        {0, 1},
        // down
        {1, 0},
        // left
        {0, -1},
        // up
        {-1, 0}
    };
};
  • 空间复杂度是 O(m x n),应该可以将复杂度降低到 O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值