-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
46 lines (36 loc) · 1.26 KB
/
SpiralMatrix.java
File metadata and controls
46 lines (36 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
//time:o(n)
//space: o(n)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix == null || matrix.length == 0 ) return res;
int rowBegin = 0, rowEnd = matrix.length-1;
int colBegin = 0, colEnd = matrix[0].length-1;
while(rowBegin <= rowEnd && colBegin <= colEnd){
//iteration the first row
for(int i = colBegin; i <= colEnd; i++){
res.add(matrix[rowBegin][i]);
}
rowBegin++;
//iteration the last col
for(int i = rowBegin; i <= rowEnd; i++){
res.add(matrix[i][colEnd]);
}
colEnd --;
// check if already last row or col
if(rowBegin <= rowEnd){
for(int i = colEnd; i >= colBegin; i--){
res.add(matrix[rowEnd][i]);
}
}
rowEnd --;
if(colBegin <= colEnd){
for(int i = rowEnd; i >= rowBegin; i--){
res.add(matrix[i][colBegin]);
}
}
colBegin ++;
}
return res;
}
}