搜索此博客

2012年8月16日星期四

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

01 public ArrayList<Integer> spiralOrder(int[][] matrix) {
02 
03   ArrayList<Integer> result=new ArrayList<Integer>();
04 
05   int m=matrix.length;
06   if(m==0)
07     return result;
08 
09   else if(m==1)
10   {
11     int n=matrix[0].length;
12     for(int j=0;j<n;j++)
13     {
14       result.add(matrix[0][j]);
15     
16     }
17     return result;
18   }
19   else
20   {
21     int n=matrix[0].length;
22     if(n==1)
23     {
24       for(int i=0;i<m;i++)
25       {
26         result.add(matrix[i][0]);
27       
28       }
29       return result;
30     }
31   
32     else
33     {
34     
35       int rowStart=0;
36       int rowEnd=m-1;
37       int colStart=0;
38       int colEnd=n-1;
39     
40       while(m>=2 && n>=2 &&rowStart<rowEnd && colStart<colEnd)
41       {
42         for(int col=colStart;col<colEnd;col++)
43         {
44           result.add(matrix[rowStart][col]);
45         }
46         for(int row=rowStart;row<rowEnd;row++)
47         {
48           result.add(matrix[row][colEnd]);
49         
50         }
51         for(int col=colEnd;col>colStart;col--)
52         {
53           result.add(matrix[rowEnd][col]);
54         }
55         for(int row=rowEnd;row>rowStart;row--)
56         {
57           result.add(matrix[row][colStart]);
58         }
59         m=m-2;
60         n=n-2;
61         rowStart++;
62         rowEnd--;
63         colStart++;
64         colEnd--;
65       }
66     
67       if(m>1 && n==1)
68       {
69         for(int row=rowStart;row<=rowEnd;row++)
70         {
71           result.add(matrix[row][colStart]);
72         }
73       }
74       else if(n>1 && m==1)
75       {
76         for(int col=colStart;col<=colEnd;col++)
77         {
78           result.add(matrix[rowStart][col]);
79         }
80       }
81       else if(m==1 && n==1)
82       {
83         result.add(matrix[rowStart][colStart]);
84       }
85     
86     
87     }
88   }
89 
90   return result;
91 }

没有评论:

发表评论