-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spiral_Matrix.java
39 lines (36 loc) · 1.08 KB
/
Spiral_Matrix.java
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
https://leetcode.com/problems/spiral-matrix/
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List <Integer> res = new ArrayList();
if(matrix.length==0){
return res;
}
int rowBegin = 0;
int rowEnd = matrix.length-1;
int columnBegin = 0;
int columnEnd = matrix[0].length-1;
while(rowBegin<=rowEnd && columnBegin<=columnEnd){
for(int i = columnBegin;i<=columnEnd;i++){
res.add(matrix[rowBegin][i]);
}
rowBegin++;
for(int i = rowBegin;i<=rowEnd;i++){
res.add(matrix[i][columnEnd]);
}
columnEnd--;
if(rowBegin<=rowEnd){
for(int i = columnEnd;i>=columnBegin;i--){
res.add(matrix[rowEnd][i]);
}
}
rowEnd--;
if(columnBegin<=columnEnd){
for(int i=rowEnd;i>=rowBegin;i--){
res.add(matrix[i][columnBegin]);
}
}
columnBegin++;
}
return res;
}
}