Skip to content

Commit f246990

Browse files
author
sangbeenmoon
committed
solved spiral-matrix.
1 parent 716fd2a commit f246990

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

spiral-matrix/sangbeenmoon.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# 우 -> 하 -> 좌 -> 상
2+
3+
class Solution:
4+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
5+
dx = [1, 0, -1, 0]
6+
dy = [0, 1, 0, -1]
7+
8+
rows, cols = len(matrix), len(matrix[0])
9+
10+
visited = [[False] * cols for _ in range(rows)]
11+
12+
answer = []
13+
14+
def dfs(xx: int, yy:int, d:int):
15+
16+
i = d
17+
cnt = 0
18+
while cnt <= 5:
19+
nx = xx + dx[i]
20+
ny = yy + dy[i]
21+
22+
if 0 <= nx and nx < cols and 0 <= ny and ny < rows:
23+
if not visited[ny][nx]:
24+
visited[ny][nx] = True
25+
answer.append(matrix[ny][nx])
26+
dfs(nx,ny,i)
27+
return
28+
if i == 3:
29+
i = 0
30+
else:
31+
i = i + 1
32+
cnt = cnt + 1
33+
34+
35+
36+
visited[0][0] = True
37+
answer.append(matrix[0][0])
38+
dfs(0,0,0)
39+
40+
return answer

0 commit comments

Comments
 (0)