forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpiralMatrix.java
32 lines (31 loc) · 1.21 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
import java.util.ArrayList;
import java.util.List;
public class SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
final List<Integer> result = new ArrayList<>();
final int rows = matrix.length, columns = matrix[0].length, elements = rows * columns;
for (int i = 0, top = 0, bottom = rows, left = 0, right = columns ; ; ) {
for (int row = top, column = left ; column < right ; column++, i++) {
result.add(matrix[row][column]);
}
top++;
if (i == elements) break;
for (int row = top, column = right - 1 ; row < bottom ; row++, i++) {
result.add(matrix[row][column]);
}
right--;
if (i == elements) break;
for (int row = bottom - 1, column = right - 1 ; column >= left ; column--, i++) {
result.add(matrix[row][column]);
}
bottom--;
if (i == elements) break;
for (int row = bottom - 1, column = left ; row >= top ; row--, i++) {
result.add(matrix[row][column]);
}
left++;
if (i == elements) break;
}
return result;
}
}