Skip to content

Commit 01bd5c4

Browse files
author
sejineer
committed
spiral-matrix solution
1 parent ac98ea6 commit 01bd5c4

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

spiral-matrix/sejineer.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
시간 복잡도: O(n * m)
3+
공간 복잡도: O(n * m)
4+
"""
5+
class Solution:
6+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
7+
n, m = len(matrix), len(matrix[0])
8+
dx = [1, 0, -1, 0]
9+
dy = [0, 1, 0, -1]
10+
state = 0
11+
vis = [[False] * m for _ in range(n)]
12+
13+
result = [matrix[0][0]]
14+
vis[0][0] = True
15+
x, y = 0, 0
16+
17+
while len(result) < n * m:
18+
nx = x + dx[state % 4]
19+
ny = y + dy[state % 4]
20+
21+
if not (0 <= nx < m) or not (0 <= ny < n) or vis[ny][nx]:
22+
state += 1
23+
continue
24+
25+
vis[ny][nx] = True
26+
result.append(matrix[ny][nx])
27+
x, y = nx, ny
28+
29+
return result

0 commit comments

Comments
 (0)