力扣54. 螺旋矩阵

模拟

  • 思路:
    • 转向表示:使用行下标和列下标变化;
      • 比如向上:行下标 - 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)

相关推荐

  1. 54. 螺旋矩阵

    2024-01-21 00:16:03       42 阅读
  2. 59-螺旋矩阵

    2024-01-21 00:16:03       42 阅读
  3. 100】54.螺旋矩阵

    2024-01-21 00:16:03       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-21 00:16:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-21 00:16:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-21 00:16:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-21 00:16:03       20 阅读

热门阅读

  1. logback日志记录器

    2024-01-21 00:16:03       33 阅读
  2. C# 十大排序算法

    2024-01-21 00:16:03       30 阅读
  3. 第二章 变量与基本类型(上)

    2024-01-21 00:16:03       27 阅读
  4. 在vue中如何优雅的封装第三方组件

    2024-01-21 00:16:03       46 阅读
  5. 【Effective C++】让自己习惯C++

    2024-01-21 00:16:03       38 阅读
  6. 关于Qt Creator 的项目创建

    2024-01-21 00:16:03       39 阅读
  7. 10 快速排序-左右指针法

    2024-01-21 00:16:03       33 阅读
  8. 根据自己修改后的容器制作镜像并上传docker hub

    2024-01-21 00:16:03       34 阅读
  9. wpf C# partial关键字:把一个类分成几个

    2024-01-21 00:16:03       41 阅读
  10. vue-项目打包、配置路由懒加载

    2024-01-21 00:16:03       46 阅读