力扣热门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;
    }
}
相关推荐
tankeven5 小时前
HJ176 【模板】滑动窗口
c++·算法
网域小星球6 小时前
C 语言从 0 入门(十二)|指针与数组:数组名本质、指针遍历数组
c语言·算法·指针·数组·指针遍历数组
冰糖拌面6 小时前
二叉树遍历-递归、迭代、Morris
算法
碧海银沙音频科技研究院6 小时前
虚拟机ubuntu与windows共享文件夹(Samba共享)解决WSL加载SI工程满卡问题
人工智能·深度学习·算法
CoovallyAIHub6 小时前
ICLR 2026 | VLM自己学会调检测器:VTool-R1用强化学习教视觉模型使用工具推理
算法·架构·github
CoovallyAIHub6 小时前
RK3588上111 FPS:轻量YOLOv8+异步视频处理系统实现无人机自主电力巡检
算法·架构·github
炽烈小老头7 小时前
【每天学习一点算法 2026/04/13】两数相除
学习·算法
嘻嘻哈哈樱桃7 小时前
俄罗斯套娃信封问题力扣--354
算法·leetcode·职场和发展
田梓燊7 小时前
2026/4/12 leetcode 1320
算法·leetcode·职场和发展
j_xxx404_7 小时前
力扣题型--链表(两数相加|两两交换链表中的节点|重排链表)
数据结构·c++·算法·leetcode·蓝桥杯·排序算法