Skip to content

Commit 114f46c

Browse files
committed
feat: solve spiral matrix
1 parent 112a38b commit 114f46c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

spiral-matrix/GangBean.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
/**
3+
1. understanding
4+
- 3 x 3 = N x M
5+
- (1,2,3) -> (6,9) // (8,7) -> (4) // (5)
6+
- upper: step M count, N -= 1 // right: step N count, M -= 1 // bottom: step M count, N -= 1 // left: step N count, M -= 1
7+
2. complexity:
8+
- time: O(N * M)
9+
- space: O(1)
10+
*/
11+
public List<Integer> spiralOrder(int[][] matrix) {
12+
int r = 0;
13+
int c = -1;
14+
int dir = 1;
15+
int N = matrix.length;
16+
int M = matrix[0].length;
17+
List<Integer> ret = new ArrayList<>();
18+
19+
while (0 < N && 0 < M) {
20+
for (int i = 0; i < M; i++) {
21+
c += dir;
22+
ret.add(matrix[r][c]);
23+
}
24+
N -= 1;
25+
for (int i = 0; i < N; i++) {
26+
r += dir;
27+
ret.add(matrix[r][c]);
28+
}
29+
M -= 1;
30+
31+
dir *= -1;
32+
}
33+
34+
return ret;
35+
}
36+
}
37+

0 commit comments

Comments
 (0)