54.螺旋矩阵

题目描述

题目描述

题解(按层模拟,边界收缩法)

思路

边界收缩法思路

代码

java 复制代码
import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        // 处理边界条件:空矩阵直接返回
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }

        // 定义四个方向的边界
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        while (true) {
            // 1. 向右移动:遍历 top 层,从 left 到 right
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            top++; // top 层遍历完,上边界下移
            if (top > bottom) break; // 若越界说明全部遍历完了

            // 2. 向下移动:遍历 right 列,从 top 到 bottom
            for (int i = top; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            right--; // right 列遍历完,右边界左移
            if (left > right) break;

            // 3. 向左移动:遍历 bottom 层,从 right 到 left
            for (int i = right; i >= left; i--) {
                result.add(matrix[bottom][i]);
            }
            bottom--; // bottom 层遍历完,下边界上移
            if (top > bottom) break;

            // 4. 向上移动:遍历 left 列,从 bottom 到 top
            for (int i = bottom; i >= top; i--) {
                result.add(matrix[i][left]);
            }
            left++; // left 列遍历完,左边界右移
            if (left > right) break;
        }

        return result;
    }
}

复杂度分析

  • 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。
  • 空间复杂度:O(1)。除了输出数组以外,空间复杂度是常数。
相关推荐
Robot_Nav2 小时前
MPPI 局部规划器实验设计讲解
人工智能·算法·mppi
Lhappy嘻嘻2 小时前
Java 并发编程(六)|并发进阶高频:CAS、锁升级
java·开发语言
mingo_敏2 小时前
Mean-Teacher 均值教师自训练框架详解
算法·均值算法
要开心吖ZSH2 小时前
MVCC 进阶:快照读 vs 当前读、幻读与 Next-Key Lock
java·数据库·sql·mysql·mvcc
京韵养生记2 小时前
【无标题】
java·服务器·前端
小强库计算机毕业设计2 小时前
源码分享Spring Boot + Vue3 的校园社团管理系统
java·spring boot·后端·计算机毕业设计
星空露珠2 小时前
迷你世界UGc3.0脚本Wiki[剧情动画模块管理接口 Timeline]
开发语言·数据结构·算法·游戏·lua
笨笨没好名字2 小时前
Leetcode刷题python3版第一周(下)
linux·算法·leetcode
格子软件2 小时前
2026年分布式GEO代理流量调度:源码级状态机防重挂实战
java·vue.js·人工智能·spring boot·分布式·vue