Skip to content

Commit 237811b

Browse files
committed
solve(w06): 54. Spiral Matrix
1 parent ded4f69 commit 237811b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

โ€Žspiral-matrix/seungriyou.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# https://leetcode.com/problems/spiral-matrix/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
7+
"""
8+
[Complexity]
9+
- TC: O(m * n) (m = row, n = col)
10+
- SC: O(1) (๊ฒฐ๊ณผ์šฉ ๋ฐฐ์—ด res ์ œ์™ธ)
11+
12+
[Approach]
13+
์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ ์ˆœํšŒํ•˜๋„๋ก, ๋ฐฉ๋ฌธ ํ‘œ์‹œ & ๋ฐฉํ–ฅ ์ „ํ™˜์„ ํ•˜๋ฉด์„œ res์— ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.
14+
์ด๋•Œ, ๋ฐฉ๋ฌธ ํ‘œ์‹œ๋ฅผ inplace๋กœ ํ•œ๋‹ค๋ฉด ์ถ”๊ฐ€ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ๋‹ค.
15+
"""
16+
17+
# ๋ฐฉํ–ฅ: ์šฐ -> ํ•˜ -> ์ขŒ -> ์ƒ
18+
dr, dc = [0, 1, 0, -1], [1, 0, -1, 0]
19+
row, col = len(matrix), len(matrix[0])
20+
21+
r, c, d = 0, 0, 0
22+
res = [matrix[r][c]]
23+
matrix[r][c] = "."
24+
25+
while len(res) < row * col:
26+
# ๋‹ค์Œ ์œ„์น˜ ํ›„๋ณด ๊ตฌํ•˜๊ธฐ
27+
nr, nc = r + dr[d], c + dc[d]
28+
29+
# ๋‹ค์Œ ์œ„์น˜ ํ›„๋ณด๊ฐ€ (1) ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ๊ฑฐ๋‚˜ (2) ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ์œ„์น˜๋ผ๋ฉด, ๋ฐฉํ–ฅ ํ‹€๊ธฐ
30+
if not (0 <= nr < row and 0 <= nc < col) or matrix[nr][nc] == ".":
31+
d = (d + 1) % 4
32+
nr, nc = r + dr[d], c + dc[d]
33+
34+
# res์— ์ถ”๊ฐ€ & ๋ฐฉ๋ฌธ ํ‘œ์‹œ
35+
res.append(matrix[nr][nc])
36+
matrix[nr][nc] = "."
37+
38+
# ์ด๋™
39+
r, c = nr, nc
40+
41+
return res

0 commit comments

Comments
ย (0)