leetcode -- 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].

 

 1 public class Solution {
 2     public ArrayList<Integer> spiralOrder(int[][] matrix) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         ArrayList<Integer> result = new ArrayList<Integer>();
 6         int rows = matrix.length;
 7         if(rows == 0){
 8             return result;
 9         }
10         int cols = matrix[0].length;
11         if(cols == 0)
12             return result;
13             
14         int start = 0;
15         while(rows > start * 2 && cols > start * 2){
16             printCircle(matrix, rows, cols, start, result);
17             start ++;
18         }
19         return result;
20     }
21     
22     public void printCircle(int[][] matrix, int rows, int cols, int start, ArrayList<Integer> result){
23         int endX = cols - 1 - start;
24         int endY = rows - 1 - start;
25         
26         // print up
27         for(int i = start; i <= endX; i++){
28             result.add(matrix[start][i]);
29         }
30         
31         // print right
32         if(endY > start){
33             for(int i = start + 1; i <= endY; i ++){
34                 result.add(matrix[i][endX]);
35             }
36         }
37         // print down
38         if(endX > start && endY > start){
39             for(int i = endX - 1; i >= start; i--){
40                 result.add(matrix[endY][i]);
41             }
42         }
43         // print left
44         if(endX > start && endY - 1 > start){
45             for(int i = endY - 1; i > start; i--){
46                 result.add(matrix[i][start]);
47             }
48         }
49     }
50 }

 

posted @ 2013-08-07 22:15  feiling  阅读(309)  评论(0编辑  收藏  举报