程序媛詹妮弗
终身学习

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

 

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

 

题意:

按螺旋方式遍历矩阵。

 

Solution1: Simulation the process and implement it.

 

code

 1 class Solution {
 2       public List<Integer> spiralOrder(int[][] matrix) {
 3         List<Integer> res = new ArrayList<>();
 4         if(matrix.length == 0 || matrix[0].length == 0) return res;
 5 
 6         int top = 0;
 7         int bottom = matrix.length-1;
 8         int left = 0;
 9         int right = matrix[0].length-1;
10 
11         while(true){
12             for(int i = left; i <= right; i++) {
13                 res.add(matrix[top][i]);
14             }
15             top++;
16             if(left > right || top > bottom) break;
17 
18             for(int i = top; i <= bottom; i++) {
19                 res.add(matrix[i][right]);
20             }
21             right--;
22             if(left > right || top > bottom) break;
23 
24             for(int i = right; i >= left; i--) {
25                 res.add(matrix[bottom][i]);
26             }
27             bottom--;
28             if(left > right || top > bottom) break;
29 
30             for(int i = bottom; i >= top; i--){
31                 res.add(matrix[i][left]);
32             }
33             left++;
34             if(left > right || top > bottom) break;
35         }
36         return res;
37     }
38 }

 

posted on 2019-04-18 17:55  程序媛詹妮弗  阅读(111)  评论(0编辑  收藏  举报