forked from prakashshuklahub/Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
54 Spiral Matrix
51 lines (40 loc) · 1.19 KB
/
54 Spiral Matrix
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
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList();
int row = matrix.length;
if(row ==0 )return list;
int col = matrix[0].length;
int l = 0 , r = col-1 , t = 0 , b = row-1 , d = 0;
while(l<=r && t<=b){
if(d==0){
for(int i=l;i<=r;i++){
list.add(matrix[t][i]);
}
d=1;t++;
}else if(d==1){
for(int i=t;i<=b;i++){
list.add(matrix[i][r]);
}
d=2;r--;
}else if (d==2){
for(int i =r;i>=l;i--){
list.add(matrix[b][i]);
}
d=3;b--;
}else if (d==3){
for(int i = b;i>=t;i--){
list.add(matrix[i][l]);
}
d=0;l++;
}
}
return list;
}