Skip to content

Commit 2ed35c8

Browse files
add post '(Leetcode) 54 - Spiral Matrix 풀이'
1 parent a561d25 commit 2ed35c8

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed

_posts/2024-07-30-leetcode-54.md

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
---
2+
layout: post
3+
title: (Leetcode) 54 - Spiral Matrix 풀이
4+
categories: [스터디-알고리즘]
5+
tags: [자바, java, 리트코드, Leetcode, 알고리즘, Array, Matrix, Simulation]
6+
date: 2024-07-30 15:00:00 +0900
7+
toc: true
8+
---
9+
10+
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다.
11+
12+
[https://neetcode.io/practice](https://neetcode.io/practice)
13+
14+
---
15+
16+
[https://leetcode.com/problems/spiral-matrix/description/](https://leetcode.com/problems/spiral-matrix/description/)
17+
18+
## 내가 작성한 풀이
19+
20+
복잡한 부분은 없다. 문제에서 설명된 spiral 순회 방식을 그대로 코드로 옮기면 된다.
21+
22+
![spiral](/assets/images/2024-07-30-leetcode-54/spiral1.jpg)
23+
24+
```java
25+
class Solution {
26+
27+
final int VISITED = 101;
28+
29+
public List<Integer> spiralOrder(int[][] matrix) {
30+
List<Integer> ordered = new ArrayList<>();
31+
32+
int i = 0;
33+
int j = 0;
34+
int depth = 0; // 한 바퀴 돌 때 마다 안쪽으로 들어가게 됨.
35+
36+
int startI = Integer.MIN_VALUE;
37+
int startJ = Integer.MIN_VALUE;
38+
39+
while (!(i == startI && j == startJ)) {
40+
startI = i;
41+
startJ = j;
42+
43+
// 마지막에서 i++ 을 진행하는데 이로 인해서 범위를 초과하는 것을 방지
44+
if (i == matrix.length) {
45+
break;
46+
}
47+
48+
// 오른쪽으로 이동
49+
while (j < matrix[0].length - depth) {
50+
update(matrix, i, j, ordered);
51+
j++;
52+
}
53+
j--;
54+
55+
// 아래로 이동
56+
while (i < matrix.length - depth) {
57+
update(matrix, i, j, ordered);
58+
i++;
59+
}
60+
i--;
61+
62+
// 왼쪽으로 이동
63+
while (j > depth - 1) {
64+
update(matrix, i, j, ordered);
65+
j--;
66+
}
67+
j++;
68+
69+
// 위로 이동
70+
while (i > depth - 1) {
71+
update(matrix, i, j, ordered);
72+
i--;
73+
}
74+
i++;
75+
76+
// while 조건에 걸리지 않도록 다음 칸으로 이동
77+
i++;
78+
j++;
79+
80+
depth++;
81+
}
82+
83+
return ordered;
84+
}
85+
86+
private void update(int[][] matrix, int i, int j, List<Integer> ordered) {
87+
if (i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length) {
88+
return;
89+
}
90+
91+
if (matrix[i][j] != VISITED) {
92+
ordered.add(matrix[i][j]);
93+
}
94+
matrix[i][j] = VISITED;
95+
}
96+
}
97+
```
98+
99+
## TC, SC
100+
101+
n은 matrix의 모든 아이템의 수를 한다고 하였을 때, 시간복잡도는 `O(n)`, 공간복잡도는 `O(1)` 이다. (공간복잡도의 경우 결과를 위해 생성되는 List는 계싼에서 제외함.)
9.92 KB
Loading

0 commit comments

Comments
 (0)