54. Spiral Matrix

就是实现题。于是我用了一个半小时 = =心好累

如果layer数是奇数的时候要多处理一下

 1     public List<Integer> spiralOrder(int[][] matrix) {
 2         List<Integer> res = new ArrayList<Integer>();
 3         if(matrix == null || matrix.length == 0) {
 4             return res;
 5         }
 6         int row = matrix.length;//row
 7         int col = matrix[0].length;//col
 8         int min = Math.min(row, col);
 9         int layer = min/2;
10         for(int level = 0; level < layer; level++) {
11             for(int i = level; i < col-1-level; i++) {
12                 res.add(matrix[level][i]);
13             }
14             for(int i = level; i < row-1-level; i++) {
15                 res.add(matrix[i][col-1-level]);
16             }
17             for(int i = level; i < col-1-level; i++) {
18                 res.add(matrix[row-1-level][col-1-i]);
19             }
20             for(int i = level; i < row-1-level; i++) {
21                 res.add(matrix[row-1-i][level]);
22             }
23         }
24         if(min % 2 == 1) {
25             if(min == col) {
26                 for(int i = layer; i < row-layer; i++) {
27                     res.add(matrix[i][layer]);
28                 }
29             } else {
30                 for(int i = layer; i < col-layer; i++) {
31                     res.add(matrix[layer][i]);
32                 }
33             }
34         }
35         System.out.println(res);
36         return res;
37     }

 

posted @ 2016-03-04 07:03  warmland  阅读(133)  评论(0编辑  收藏  举报