[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;
    }
}
相关推荐
Resean02238 小时前
Spring 源码分析(二)配置类的解析与扫描
java·后端·spring
小毛球.8 小时前
第 3 篇:IDEA 最新版下载与完整安装教程(Mac)
java·macos·intellij-idea·idea
Misnearch10 小时前
ScheduledExecutorService
java·线程池
ashiho10 小时前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
T_Wizard11 小时前
AI 回复为什么要转圈 3 秒才「啪」一下全出来?把流式输出拆开看,顺便踩了 6 个坑
java·ai编程
CoderYanger11 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第二弹)
java·数据库·面试·职场和发展·java-ee·tomcat·mybatis
小满、13 小时前
Java 值传递
java·java 值传递
IT枫斗者枫哥13 小时前
Java 异步导出只测最终行数,为什么下载时仍会少一行?
java·后端
张紫娃13 小时前
idea 如何看一个类的 .class 文件
java·ide·intellij-idea
南宫鑫13 小时前
Java底层实现
java