-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-54.java
More file actions
66 lines (63 loc) · 2.15 KB
/
lc-54.java
File metadata and controls
66 lines (63 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Solution {
public List<Integer> spiralOrder(int[][] m) {
if(m.length == 0 || m[0].length == 0) return new ArrayList();
boolean[][] tm = new boolean[m.length][m[0].length];
List<Integer> res = new ArrayList();
int finaln = m.length * m[0].length;
//先水平,后垂直
int i = 0, j = 0;
int num = 0;
int direction = 1;
while(num < finaln) {
switch(direction) {
case 1: //向右
while(j<=m[0].length-1 && !tm[i][j]) {
System.out.println(i + " " + j);
res.add(m[i][j]);
tm[i][j] = true;
num++;
j++;
}
i++;
j--;
break;
case 2: //向下
while(i <= m.length-1 && !tm[i][j]) {
System.out.println(i + " " + j);
res.add(m[i][j]);
tm[i][j] = true;
num++;
i++;
}
j--;
i--;
break;
case 3: //向左
while(j>=0 && !tm[i][j]) {
System.out.println(i + " " + j);
res.add(m[i][j]);
tm[i][j] = true;
j--;
num++;
}
//System.out.println(i + " " + j);
i--;
j++;
break;
case 4: //向上
while(!tm[i][j]) {
System.out.println(i + " " + j);
res.add(m[i][j]);
tm[i][j] = true;
i--;
num++;
}
j++;
i++;
break;
}
direction = direction == 4?1:direction+1;
}
return res;
}
}