代码:
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
矩阵题目:顺时针顺序打印矩阵
depth_codeYin2024-05-08 10:08
相关推荐
daidaidaiyu4 小时前
一文学习 工作流开发 BPMN、 FlowableSuniaWang5 小时前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》sheji34165 小时前
【开题答辩全过程】以 基于springboot的扶贫系统为例,包含答辩的问题和答案m0_726965986 小时前
面面面,面面(1)xuhaoyu_cpp_java6 小时前
过滤器与监听器学习程序员小假7 小时前
我们来说一下 b+ 树与 b 树的区别Meepo_haha7 小时前
Spring Boot 条件注解:@ConditionalOnProperty 完全解析sheji34168 小时前
【开题答辩全过程】以 基于springboot的房屋租赁系统的设计与实现为例,包含答辩的问题和答案木井巳8 小时前
【递归算法】子集
