力扣热门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;
    }
}
相关推荐
其实防守也摸鱼13 小时前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
Nuanyt13 小时前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
w_zero_one16 小时前
递归算法(一)
java·开发语言·算法
圣保罗的大教堂17 小时前
leetcode 3736. 最小操作次数使数组元素相等 III 简单
leetcode
文丑颜不良啊17 小时前
LeetCode1881~1990题目解析
java·leetcode
风影同志7832418 小时前
20 个比特能装下多少行情?——实测拆解 Kronos 的 K 线分词器
算法
写的都是BUG19 小时前
APK 里的钥匙,一直就放在门口:聊聊加固真正该做什么
前端·算法
地平线开发者19 小时前
CLIP 的零样本分类:一组文本如何变成图像分类器?
算法
京东云开发者20 小时前
从“会生成”到“能生产”:萤火虫 AIGC 平台的 AI Infra 实践
算法·aigc·产品