-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path54.java
More file actions
47 lines (40 loc) · 1.4 KB
/
54.java
File metadata and controls
47 lines (40 loc) · 1.4 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
47
import java.util.LinkedList;
import java.util.List;
/**
* 54. Spiral Matrix
*
* Given an m x n matrix, return all elements of the matrix in spiral order.
*/
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new LinkedList<>();
int rowTop = 0;
int rowBottom = matrix.length - 1;
int colLeft = 0;
int colRight = matrix[0].length - 1;
int terminate = matrix.length * matrix[0].length;
while (result.size() < terminate) {
// traverse right
for (int i = colLeft; i <= colRight && result.size() < terminate; i++) {
result.add(matrix[rowTop][i]);
}
rowTop++;
// traverse down
for (int i = rowTop; i <= rowBottom && result.size() < terminate; i++) {
result.add(matrix[i][colRight]);
}
colRight--;
// traverse left
for (int i = colRight; i >= colLeft && result.size() < terminate; i--) {
result.add(matrix[rowBottom][i]);
}
rowBottom--;
// traverse up
for (int i = rowBottom; i >= rowTop && result.size() < terminate; i--) {
result.add(matrix[i][colLeft]);
}
colLeft++;
}
return result;
}
}