螺旋矩阵打印
from:http://blog.51cto.com/acevi/2141009
题目如下
分析
不难发现,按照顺时针螺旋顺序遍历矩阵其实就只有四个方向:顶层行从左往右;右边列从上到下;底层行从右往左;左边列从下往上。遍历完这四个方向之后就表示已经遍历完了一圈,下一圈也同样是这四个方向,只是初始位置和结束位置会在每一轮遍历之后发生变化。
下面介绍两种方法,思想基本一致,不同之处是对边界的判断和位置的移动。
方法一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | public class SpiralMatrix { public static List<Integer> spiralMatrixOlder( int [][] matrix) { List<Integer> res = new ArrayList<Integer>(); if (matrix.length == 0 ) return res; int rowBegin = 0 ; int colBegin = 0 ; int rowEnd = matrix.length - 1 ; //行 int colEnd = matrix[ 0 ].length - 1 ; //列 /* * Time Complexity: O(N) * Space Complexity:O(N)*/ while (rowBegin <= rowEnd && colBegin <= colEnd){ //底层行从左往右 for ( int i = colBegin;i <= colEnd;i++) { res.add(matrix[rowBegin][i]); } rowBegin++; //处理完一行后往下移一行 //右边列从上往下 for ( int i = rowBegin ;i <= rowEnd;i++) { res.add(matrix[i][colEnd]); } colEnd--; //处理完一列往前移一列 //底层行从右往左 if (rowBegin <= rowEnd) { for ( int j = colEnd;j>=colBegin;j--){ res.add(matrix[rowEnd][j]); } rowEnd--; } //左边列从下往上 if (colBegin <= colEnd) { for ( int j = rowEnd;j >= rowBegin ; j--) { res.add(matrix[j][colBegin]); } colBegin++; } } return res; } 类似的: |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public class Solution { public int [][] generateMatrix( int n) { int [][] res = new int [n][n]; int total = n * n; int num = 1 ; int rowBegin = 0 ; int rowEnd = n - 1 ; int colBegin = 0 ; int colEnd = n - 1 ; while (num < = total) { / / traverse right (y changes) for ( int y = colBegin; y< = colEnd; y + + ) res[rowBegin][y] = num + + ; rowBegin + + ; / / move down one row / / traverse down (x changes) for ( int x = rowBegin; x< = rowEnd; x + + ) res[x][colEnd] = num + + ; colEnd - - ; / / move left one column / / traverse left (y changes) for ( int y = colEnd; y> = colBegin; y - - ) res[rowEnd][y] = num + + ; rowEnd - - ; / / move up one row / / traverse up (x changes) for ( int x = rowEnd; x> = rowBegin; x - - ) res[x][colBegin] = num + + ; colBegin + + ; / / move right one column } return res; } } |
1 | |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2018-01-08 神经网络中的激活函数——加入一些非线性的激活函数,整个网络中就引入了非线性部分,sigmoid 和 tanh作为激活函数的话,一定要注意一定要对 input 进行归一话,但是 ReLU 并不需要输入归一化
2018-01-08 CNN中的局部连接(Sparse Connectivity)和权值共享
2018-01-08 AdaBoostClassifier实战