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)。除了输出数组以外,空间复杂度是常数。
相关推荐
Tisfy24 分钟前
LeetCode 3876.构造奇偶一致的数组 II:三种情况分类讨论(其实还是脑筋急转弯)
算法·leetcode·题解·脑筋急转弯
乐迪信息1 小时前
智慧港口船舶AI算法实现在线状态监测
大数据·人工智能·深度学习·算法·计算机视觉
zww89491111 小时前
匿名树洞系统开发实战:从需求分析到部署指南
java·eclipse
黑马程序员毕设3 小时前
基于Java的医院药品管理系统的优化设计与实现
java·开发语言·spring boot·小程序·架构·课程设计·毕设
木井巳3 小时前
【BFS/DFS 解决 FloodFill 算法】太平洋大西洋水流问题
java·算法·leetcode·深度优先·广度优先·宽度优先·推荐算法
心抵鹊3 小时前
归并排序之翻转对(hard)
数据结构·算法
白山编程大哥3 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
devpotato3 小时前
缓存与数据库更新顺序不一致问题
java·数据库·redis
shehuiyuelaiyuehao3 小时前
算法34,位运算符操作,总结
算法
xcl09254 小时前
酒馆预约系统开发实战:从需求分析到上线全流程指南
java·spring boot·需求分析