54. 螺旋矩阵

 

 

 

 

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

时间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     }

 

posted @ 2021-05-27 09:52  jchen104  阅读(84)  评论(0编辑  收藏  举报