首页 > 其他 > 详细

54. 螺旋矩阵

时间:2021-05-27 11:12:12      阅读:33      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

技术分享图片

 

 

采用模拟的方案顺时针遍历所有元素

时间O(m*n)(需要遍历所有节点),空间O(1)

 1     public List<Integer> spiralOrder(int[][] matrix) {
 2         LinkedList<Integer> res = new LinkedList<>();
 3         if(matrix==null || matrix.length==0) return res;
 4         int left=0,right=matrix[0].length-1,top=0,bottom=matrix.length-1;
 5         int numEle = matrix.length*matrix[0].length;
 6         while(numEle>0){
 7             // 由左向右遍历
 8             for(int i=left; i<=right && numEle>0 ;i++){
 9                 res.add(matrix[top][i]);
10                 numEle--;
11             }
12             top++;
13             // 由上向下遍历
14             for(int i=top; i<=bottom && numEle>0 ; i++){
15                 res.add(matrix[i][right]);
16                 numEle--;
17             }
18             right--;
19             // 由右向左遍历
20             for(int i=right;i>=left && numEle>0;i--){
21                 res.add(matrix[bottom][i]);
22                 numEle--;
23             }
24             bottom--;
25             // 由下向上遍历
26             for(int i=bottom;i>=top && numEle>0;i--){
27                 res.add(matrix[i][left]);
28                 numEle--;
29             }
30             left++;
31         }
32         return res;
33     }

 

54. 螺旋矩阵

原文:https://www.cnblogs.com/jchen104/p/14816614.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!