Skip to content

Commit ac05c98

Browse files
committed
add spiral matrix solution
1 parent ff65ed3 commit ac05c98

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

spiral-matrix/Tessa1217.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
/**
5+
* m * n 행렬을 시계 방향 순대로 요소를 정렬하여 반환하세요.
6+
*/
7+
class Solution {
8+
9+
public List<Integer> spiralOrder(int[][] matrix) {
10+
11+
List<Integer> spirals = new ArrayList<>();
12+
13+
int top = 0;
14+
int bottom = matrix.length - 1;
15+
int start = 0;
16+
int end = matrix[0].length - 1;
17+
18+
while (top <= bottom && start <= end) {
19+
// 우측
20+
for (int i = start; i <= end; i++) {
21+
spirals.add(matrix[top][i]);
22+
}
23+
top++;
24+
25+
// 아래
26+
for (int i = top; i <= bottom; i++) {
27+
spirals.add(matrix[i][end]);
28+
}
29+
end--;
30+
31+
// 좌측
32+
if (top <= bottom) {
33+
for (int i = end; i >= start; i--) {
34+
spirals.add(matrix[bottom][i]);
35+
}
36+
bottom--;
37+
}
38+
39+
// 위
40+
if (start <= end) {
41+
for (int i = bottom; i >= top; i--) {
42+
spirals.add(matrix[i][start]);
43+
}
44+
start++;
45+
}
46+
47+
}
48+
49+
return spirals;
50+
}
51+
52+
}
53+

0 commit comments

Comments
 (0)