-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSpiral_Matrix.java
More file actions
41 lines (38 loc) · 1.09 KB
/
Spiral_Matrix.java
File metadata and controls
41 lines (38 loc) · 1.09 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
import java.util.ArrayList;
import java.util.List;
public class Spiral_Matrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if(matrix.length==0)
return list;
int sr = 0;
int er = matrix.length-1;
int sc = 0;
int ec = matrix[0].length-1;
int totalNos = (er+1)*(ec+1);
int count = 1;
while(count<=totalNos){
for(int i = sc; i<=ec && count<=totalNos; i++){
list.add(matrix[sr][i]);
count++;
}
sr++;
for(int i = sr; i<=er && count<=totalNos; i++){
list.add(matrix[i][ec]);
count++;
}
ec--;
for(int i = ec; i>=sc && count<=totalNos; i--){
list.add(matrix[er][i]);
count++;
}
er--;
for(int i = er; i>=sr && count<=totalNos; i--){
list.add(matrix[i][sc]);
count++;
}
sc++;
}
return list;
}
}