Spiral Matrix
LeetCode https://leetcode.cn/problems/spiral-matrix/
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
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
spiralTraverse(matrix, result, 0, matrix.length, matrix[0].length);
return result;
}
private void spiralTraverse(int[][] matrix, List<Integer> result, int offset, int rowLength, int colLength) {
if (rowLength == 0 || colLength == 0) {
return;
}
if (rowLength == 1) {
for (int i = 0; i < colLength; i++) {
result.add(matrix[offset][offset + i]);
}
return;
}
if (colLength == 1) {
for (int i = 0; i < rowLength; i++) {
result.add(matrix[offset + i][offset]);
}
return;
}
// top-left to top-right
for (int i = 0; i < colLength; i++) {
result.add(matrix[offset][offset + i]);
}
// top-right to bottom-right
for (int i = 1; i < rowLength - 1; i++) {
result.add(matrix[offset + i][offset + colLength - 1]);
}
// bottom-right to bottom-left
for (int i = colLength - 1; i >= 0; i--) {
result.add(matrix[offset + rowLength - 1][offset + i]);
}
// bottom-left to top-left
for (int i = rowLength - 2; i >= 1; i--) {
result.add(matrix[offset + i][offset]);
}
// the next layer
spiralTraverse(matrix, result, offset + 1, rowLength - 2, colLength - 2);
}
}
Complexity
- Time = O(m*n)
- Space = O(1)
This post is licensed under CC BY 4.0 by the author.