[Java][Leetcode middle] 54. 螺旋矩阵

官解

采用四个变量分别记录上下左右

然后根据循环方向分别移动一格,然后判断是否需要退出循环。

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(true){
            // 左到右
            for(int i = left; i<=right ;i++) res.add(matrix[top][i]);
            // 向下一格并判断是否超出边界
            if(++top > bottom) break;

            // 上到下
            for(int i = top; i<=bottom;i++)  res.add(matrix[i][right]);
            // 左
            if(--right < left) break;

            // 右到左
            for(int i = right; i>=left;i--)  res.add(matrix[bottom][i]);
            // 上
            if(--bottom < top) break;

            // 下到上
            for(int i = bottom; i>=top;i--)  res.add(matrix[i][left]);
            // 右
            if(++left > right) break;
        }

        return res;
    }
}
相关推荐
野生技术架构师3 小时前
2026 Java 面试全套总结,八股 + 场景 + AI 相关面试考点
java·人工智能·面试
香吧香3 小时前
java服务异常日志只打印异常类型,没有堆栈定位分析
java·jvm·异常
qq_2518364574 小时前
AI 疾病自查功能SpringbootAI项目实战 · 技术实现文档
java·ai·ai编程
mmmmath_34 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z4 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
逆境不可逃4 小时前
Pi Agent 学习笔记:对话太长以后,如何压缩上下文
java
MetaLite4 小时前
JDK 8~26 核心特性一览:从 Stream 到 Scoped Values
java
wno7045 小时前
Spring Boot WebFlux增删改查
java·spring boot·后端
君顾15 小时前
上海24小时自助健身房系统开发实战指南:从架构设计到落地部署
java·开发语言·健身房
参.商.6 小时前
【Day 53】76. 最小覆盖子串
leetcode·golang