-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiral.java
More file actions
45 lines (45 loc) · 1.06 KB
/
spiral.java
File metadata and controls
45 lines (45 loc) · 1.06 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
import java.util.*;
class Solution {
public List<Integer> spiralOrder(int[][] matrix)
{
int m=matrix.length;
List<Integer>res=new ArrayList<>();
if(m==0)
return res;
int n=matrix[0].length;
int i, sr = 0, sc = 0;
int er= matrix.length-1;
int ec=matrix[0].length-1;
while (sr <=er && sc <=ec) {
//top
for (int j = sc; j <=ec; j++) {
res.add(matrix[sr][j]);
}
//right
for (i = sr+1; i <= er; i++) {
res.add(matrix[i][ec]);
}
//bottom
for (int j = ec-1; j>= sc; j--) {
if(sr==er)
{
break;
}
res.add(matrix[er][j]);
}
//left
for (i = er - 1; i >= sr+1; i--) {
if(sc==ec)
{
break;
}
res.add(matrix[i][sc]);
}
sc++;
sr++;
er--;
ec--;
}
return res;
}
}