Skip to content

Commit ee68484

Browse files
committed
add solution: spiral-matrix
1 parent 7f8423b commit ee68484

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

spiral-matrix/ZetBe.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''
2+
문제: 나선형으로 행렬을 순회하며 모든 원소를 반환
3+
풀이: 방문한 위치를 기록하는 행렬을 만들어 현재 방향으로 이동할 수 있는지 확인하며 이동, 이동할 수 없으면 방향을 바꿈
4+
시간복잡도: O(m*n) (m: 행의 수, n: 열의 수)
5+
공간복잡도: O(m*n) (방문 기록을 위한 행렬)
6+
사용한 자료구조: 리스트
7+
개인적인 회고: 문제 자체는 단순하지만 경계 조건과 방향 전환 로직을 꼼꼼히 처리해야 해서 구현에 신경을 써야 했다. 방문 기록 행렬을 사용하여 이미 방문한 위치를 피하는 방식이 직관적이고 이해하기 쉬웠다.
8+
'''
9+
10+
class Solution:
11+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
12+
v = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
13+
if len(v) == 1:
14+
return [i for i in matrix[0]]
15+
if len(v[0]) == 1:
16+
answer = []
17+
for i in matrix:
18+
for j in i:
19+
answer.append(j)
20+
return answer
21+
answer = []
22+
d = [[0, 1], [1, 0], [0, -1], [-1, 0]]
23+
i = 0
24+
y, x = 0, 0
25+
while True:
26+
if len(answer) == len(v)*len(v[0]):
27+
break
28+
v[y][x] = 1
29+
answer.append(matrix[y][x])
30+
ny = y + d[i][0]
31+
nx = x + d[i][1]
32+
if not(0 <= nx < len(v[0]) and 0 <= ny < len(v) and v[ny][nx] == 0):
33+
i = (i+1)%4
34+
ny, nx = y + d[i][0], x + d[i][1]
35+
y, x = ny, nx
36+
37+
38+
return answer
39+
40+

0 commit comments

Comments
 (0)