Skip to content

Commit e93c1d0

Browse files
committed
feat: add spiral matrix solution
1 parent e0cd3f2 commit e93c1d0

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

โ€Žspiral-matrix/mangodm-web.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
6+
"""
7+
- Idea: ๋„ค ๊ฐœ์˜ ํฌ์ธํ„ฐ(left, right, top, bottom)๋ฅผ ํ™œ์šฉํ•˜์—ฌ ํ–‰๋ ฌ์˜ ๋ฐ”๊นฅ์ชฝ๋ถ€ํ„ฐ ์•ˆ์ชฝ์œผ๋กœ ์ˆœํšŒํ•œ๋‹ค.
8+
- left, right: ํ–‰๋ ฌ์˜ ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ๋. ์ˆœํšŒํ•˜๋ฉด์„œ ์ ์  ์ขํ˜€์ง„๋‹ค.
9+
- top, bottom: ํ–‰๋ ฌ์˜ ์œ„์ชฝ๊ณผ ์•„๋ž˜์ชฝ. ์ˆœํšŒํ•˜๋ฉด์„œ ์ ์  ์ขํ˜€์ง„๋‹ค.
10+
- Time Complexity: O(m*n), m, n์€ ๊ฐ๊ฐ ์ฃผ์–ด์ง„ ํ–‰๋ ฌ(matrix)์˜ ํ–‰๊ณผ ์—ด์˜ ๊ฐœ์ˆ˜. ํ–‰๋ ฌ์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ํ•œ๋ฒˆ์”ฉ ์ ‘๊ทผํ•œ๋‹ค.
11+
- Space Complexity: O(1), ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ(result)๋ฅผ ์ œ์™ธํ•˜๊ณ  ํฌ์ธํ„ฐ๋ฅผ ์œ„ํ•œ ์ƒ์ˆ˜ ํฌ๊ธฐ์˜ ๋ณ€์ˆ˜ ์ด์™ธ์˜ ์ถ”๊ฐ€ ๊ณต๊ฐ„์€ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค.
12+
"""
13+
result = []
14+
left, right = 0, len(matrix[0])
15+
top, bottom = 0, len(matrix)
16+
17+
while left < right and top < bottom:
18+
for i in range(left, right):
19+
result.append(matrix[top][i])
20+
top += 1
21+
22+
for i in range(top, bottom):
23+
result.append(matrix[i][right - 1])
24+
right -= 1
25+
26+
if not (left < right and top < bottom):
27+
break
28+
29+
for i in range(right - 1, left - 1, -1):
30+
result.append(matrix[bottom - 1][i])
31+
bottom -= 1
32+
33+
for i in range(bottom - 1, top - 1, -1):
34+
result.append(matrix[i][left])
35+
left += 1
36+
37+
return result

0 commit comments

Comments
ย (0)