# Spiral Matrix(LintCode)

#### Spiral Matrix

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

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     /**
3      * @param matrix a matrix of m x n elements
4      * @return an integer list
5      */
6      int[][] f = new int[1000][1000];
7     public List<Integer> spiralOrder(int[][] matrix) {
8         List<Integer> list = new ArrayList<Integer>();
9         int m = matrix.length;
10         if(m == 0) return list;
11         int n = matrix[0].length;
12
13         int[][] d = new int[4][2];
14         d[0][0] = 0; d[0][1] = 1;
15         d[1][0] = 1; d[1][1] = 0;
16         d[2][0] = 0; d[2][1] = -1;
17         d[3][0] = -1; d[3][1] = 0;
18
19         int cd = 0;
20         int i = 0;
21         int j = 0;
23         f[0][0] = 1;
24         boolean flag = true;
25         while(flag) {
26             if(!isV(i,j,d[cd],m,n)){
27                 int x = 0;
28                 while(!isV(i,j,d[cd],m,n) && x < 4) {
29                     cd = (cd + 1) % 4;
30                     x++;
31                 }
32                 if(x >= 4) flag = false;
33             }else {
34                 i += d[cd][0];
35                 j += d[cd][1];
37                 f[i][j] = 1;
38             }
39         }
40
41         return list;
42     }
43
44     boolean isV(int i ,int j ,int d[] ,int m ,int n) {
45         if(i + d[0] < 0 || i + d[0] >= m) return false;
46         if(j + d[1] < 0 || j + d[1] >= n) return false;
47         if(f[i + d[0]][j + d[1]] != 0)return false;
48         return true;
49     }
50 }
View Code

posted @ 2015-12-08 22:45  -.-|  阅读(117)  评论(0编辑  收藏