力扣热门100题之螺旋矩阵

核心思路

  1. 定义四个边界:上、下、左、右

  2. 按 右 → 下 → 左 → 上 顺序遍历

  3. 每遍历完一条边,就把对应边界往内缩一圈

  4. 直到边界重合,遍历结束

关键判断

  • 遍历下排 前要判断:top <= bottom
  • 遍历左列 前要判断:left <= right防止单行 / 单列时重复遍历

四个方向(固定顺序)

  1. 上排:左 → 右
  2. 右列:上 → 下
  3. 下排:右 → 左
  4. 左列:下 → 上 走完一轮,边界全部往里缩一圈。

完整代码实现:

java 复制代码
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        // 判空
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }

        // 定义四个边界
        int top = 0; // 上边界
        int bottom = matrix.length - 1; // 下边界
        int left = 0; // 左边界
        int right = matrix[0].length - 1; // 右边界
        // 一直转圈,直到边界越界
        while (top <= bottom && left <= right) {
            // 1. 从左到右遍历上边界
            for (int j = left; j <= right; j++) {
                res.add(matrix[top][j]);
            }
            top++; // 上边界用完,向下缩

            // 2. 从上到下遍历右边界
            for (int i = top; i <= bottom; i++) {
                res.add(matrix[i][right]);
            }
            right--; // 右边界用完,向左缩

            // 3. 从右到左遍历下边界(要判断还有没有剩余行)
            if (top <= bottom) {
                for (int j = right; j >= left; j--) {
                    res.add(matrix[bottom][j]);
                }
                bottom--; // 下边界用完,向上缩
            }

            // 4. 从下到上遍历左边界(要判断还有没有剩余列)
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    res.add(matrix[i][left]);
                }
                left++; // 左边界用完,向右缩
            }
        }
        return res;
    }
}
相关推荐
饮水桶_T2 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
饮水桶_T4 小时前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AAA修煤气灶刘哥4 小时前
QQ 音乐怎么在 25 毫秒内,决定一句话该交给谁?
人工智能·算法·llm
开开心心就好5 小时前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua
geovindu17 小时前
python:DecisionTree
开发语言·后端·python·算法
geovindu18 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AllData公司负责人21 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康1 天前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长1 天前
C++:C++11特性
开发语言·c++·算法