forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralMatrix.java
48 lines (39 loc) · 1.27 KB
/
SpiralMatrix.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
40
41
42
43
44
45
46
47
48
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<Integer>();
if (matrix.length == 0) {
return ans;
}
int startRow = 0;
int endRow = matrix.length-1;
int startColumn = 0;
int endColumn = matrix[0].length - 1;
while (startRow <= endRow && startColumn <= endColumn) {
// Move towards right
for (int j = startColumn; j <= endColumn; j ++) {
ans.add(matrix[startRow][j]);
}
startRow++;
// Move towards down
for (int i = startRow; i <= endRow; i ++) {
ans.add(matrix[i][endColumn]);
}
endColumn--;
if (startRow <= endRow) {
// Move towards left
for (int j = endColumn; j >= startColumn; j --) {
ans.add(matrix[endRow][j]);
}
}
endRow--;
if (startColumn <= endColumn) {
// Move towards top
for (int i = endRow; i >= startRow; i --) {
ans.add(matrix[i][startColumn]);
}
}
startColumn ++;
}
return ans;
}
}