矩阵题目:顺时针顺序打印矩阵

代码:

复制代码
  public static List<Integer> spiralOrder(int[][] matrix) {
        //上
        int top = 0;
        //下
        int bottom = matrix.length-1;
        //左
        int left = 0;
        //右
        int right = matrix[0].length-1;
        // b决定下边界 d决定右边界
        List<Integer> order = new ArrayList<>();
        //不能跳跃打印,顺序逻辑,一方不满足 直接break
        if(matrix.length == 1){
            for(int i = 0; i < matrix[0].length; i++){
                order.add(matrix[0][i]);
            }
            return order;
        }
        if(matrix[0].length == 1){
            for(int i = 0; i < matrix.length; i++){
                order.add(matrix[i][0]);
            }
            return order;
        }
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                order.add(matrix[top][column]);
            }
            for (int row = top + 1; row <= bottom; row++) {
                order.add(matrix[row][right]);
            }
            if(left + 1 > right || top + 1 > bottom){
                break;
            }
            for (int column = right - 1; column > left; column--) {
                 order.add(matrix[bottom][column]);
            }
            for (int row = bottom; row > top; row--) {
                 order.add(matrix[row][left]);
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return order;
    }

其关键点在于 **if(left + 1 > right || top + 1 > bottom)**这句代码 其用来结束两种情况

**1.left + 1 > right :**此时已经完成了顺时针左到右的打印,所以需要+1,如果此时left+1>right,代表左右之间没有空行了,之间结束循环,返回

类比这种情况,在完成第一次顺时针打印后,left++变成1,right--变成1,但是上下之间还是有空行 ,所以如果不执行if(left + 1 > right){break;},则最后还会执行自下向上的打印,最后的打印结构会多一个5


**2.top + 1 > bottom:**这种情况是考虑到上下已经没有行了,但是左右还有行的情况,但这种情况时

类比这种情况,如果不判断top+1 > bottom则结束循环的话,那么在执行第二遍顺时针打印时,发现左右还有空间 (left = 1 right = 2)此时还会执行一个自右向左的打印,最终结果会多一个6

相关推荐
独泪了无痕15 小时前
探索Pinyin4j-Java中的拼音转换利器
java·后端
道尔柯南16 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
kingx317 小时前
Bugku 3122 谷歌小恐龙题解:纯离线逆向 Vault 的 AES-GCM 加密资源(附 Python 解密器)
java·逆向·ctf·bugku·aes-gcm
DevOpenClub19 小时前
职教高考控制线 API:招生类别枚举、筛选与空分数含义
java·数据库·高考
露天赏雪20 小时前
第3篇:Sentinel熔断降级实战:大模型接口抖动时的服务兜底方案
java·开发语言·人工智能·spring boot·spring·servlet·sentinel
天天被压力21 小时前
【A股分钟级高频数据完全手册 #06】北交所分钟级数据接口:京市股票Pro版最新分时
java·人工智能·python
天天被压力21 小时前
【A股分钟级高频数据完全手册 #05】指数历史分钟数据接口:Pro版沪深指数分时回放
java·人工智能·python
captain37621 小时前
▲统一功能——DispatcherServlet源码分析
java·spring·java-ee·log4j·maven
金銀銅鐵21 小时前
JDK 21 中 List.of 的实现细节:从 List12 到 ListN
java·后端·ai编程
yeccheng1 天前
MySQL 索引超详解:从底层 B+ 树到面试高频考点
java·开发语言·jvm·mysql·面试