-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path54.spiral-matrix.java
More file actions
52 lines (37 loc) · 1.26 KB
/
Copy path54.spiral-matrix.java
File metadata and controls
52 lines (37 loc) · 1.26 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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int top = 0;
int bottom = matrix.length-1;
int left = 0;
int right = matrix[0].length-1;
List<Integer> res = new ArrayList<>();
int dir = 1;
while(left <= right && top <= bottom){
if(dir == 1){
for(int d=left;d<=right;d++)
res.add(matrix[top][d]);
top++;
dir++;
}
else if(dir == 2){
for(int i=top;i<=bottom;i++)
res.add(matrix[i][right]);
right--;
dir++;
}
else if(dir == 3){
for(int i=right;i>=left;i--)
res.add(matrix[bottom][i]);
bottom--;
dir++;
}
else if(dir == 4){
for(int i=bottom;i>=top;i--)
res.add(matrix[i][left]);
left++;
dir = 1;
}
}
return res;
}
}