[leetcode]Spiral Matrix

Spiral Matrix

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

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

算法思路:

这道题其实是[leetcode]Spiral Matrix II的加强版(命名似乎有点本末倒置),上题是放,本题是取。道理是一样的都是扫描。

只不过上题保证了每一圈都是四条边,而本题不一定,可能是一条边,两条边,三条边,四条边均可。【其中三条边和四条边的处理时一样的】

因此在loop的时候要加上两个判断。

代码如下:

 1 public class Solution {
 2     public List<Integer> spiralOrder(int[][] matrix) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if(matrix == null || matrix.length == 0) return res;
 5         int height = matrix.length;
 6         int width = matrix[0].length;
 7         int min = Math.min(height,width) + 1;
 8         for(int i = 0; i < min >> 1; i++){
 9             for(int j = i; j < width - i; j++){
10                 res.add(matrix[i][j]);
11             }
12             for(int j = i + 1; j < height - i; j++){
13                 res.add(matrix[j][width - i - 1]);
14             }
15             if(height - i - 1 == i) continue;//只有一条边
16             for(int j = width - i - 2; j >= i; j--){
17                 res.add(matrix[height - i - 1][j]);
18             }
19             if(width - i - 1 == i) continue;//只有两条边
20             for(int j = height - i - 2; j > i; j--){
21                 res.add(matrix[j][i]);
22             }
23         }
24         return res;
25     }
26 }

木有太大难度

 

posted on 2014-08-15 15:55  喵星人与汪星人  阅读(206)  评论(0编辑  收藏  举报