Skip to content

Commit d7bb9cb

Browse files
committed
spiral-matrix solution (py)
1 parent 2706b2a commit d7bb9cb

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

โ€Žspiral-matrix/hi-rachel.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
"""
2+
- ์œ„์ชฝ ํ–‰์„ ์ˆœํšŒํ•œ ํ›„, ์ƒ๋‹จ ๊ฒฝ๊ณ„๋ฅผ 1 ์ฆ๊ฐ€
3+
- ์˜ค๋ฅธ์ชฝ ์—ด์„ ์ˆœํšŒํ•œ ํ›„, ์šฐ์ธก ๊ฒฝ๊ณ„๋ฅผ 1 ๊ฐ์†Œ
4+
- ์•„๋ž˜์ชฝ ํ–‰์„ ์ˆœํšŒํ•œ ํ›„, ํ•˜๋‹จ ๊ฒฝ๊ณ„๋ฅผ 1 ๊ฐ์†Œ
5+
- ์™ผ์ชฝ ์—ด์„ ์ˆœํšŒํ•œ ํ›„, ์ขŒ์ธก ๊ฒฝ๊ณ„๋ฅผ 1 ์ฆ๊ฐ€
6+
7+
ํƒˆ์ถœ ์กฐ๊ฑด
8+
1. ์œ„์ชฝ ํ–‰ ์ˆœํšŒ๋ฅผ ๋งˆ์น˜๊ณ  ์ƒ๋‹จ ์ธ๋ฑ์Šค๊ฐ€ ํ•˜๋‹จ ์ธ๋ฑ์Šค๋ณด๋‹ค ์ปค์ง€๋ฉด
9+
2. ์˜ค๋ฅธ์ชฝ ์—ด ์ˆœํšŒ๋ฅผ ๋งˆ์น˜๊ณ , ์šฐ์ธก ์ธ๋ฑ์Šค๊ฐ€ ์ขŒ์ธก ์ธ๋ฑ์Šค๋ณด๋‹ค ์ž‘์•„์ง€๋ฉด
10+
11+
TC: O(m * n) => ํ–‰๋ ฌ์˜ ์ €์žฅ๋œ ๋ชจ๋“  ์›์†Œ๋ฅผ ๋”ฑ 1๋ฒˆ์”ฉ๋งŒ ์ ‘๊ทผ, SC: O(1)
12+
"""
13+
14+
class Solution:
15+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
16+
top, bottom = 0, len(matrix) - 1 # ํ–‰์˜ ์ˆ˜ len(maxtrix)
17+
left, right = 0, len(matrix[0]) - 1 # ์—ด์˜ ์ˆ˜ len(maxtrix[0])
18+
19+
output = []
20+
21+
while top <= bottom and left <= right:
22+
# ์œ„์ชฝ ํ–‰ ์ˆœํšŒ
23+
for c in range(left, right + 1):
24+
output.append(matrix[top][c])
25+
top += 1
26+
27+
if top > bottom:
28+
break
29+
30+
# ์˜ค๋ฅธ์ชฝ ์—ด ์ˆœํšŒ
31+
for r in range(top, bottom + 1):
32+
output.append(matrix[r][right])
33+
right -= 1
34+
35+
if left > right:
36+
break
37+
38+
# ์•„๋ž˜์ชฝ ํ–‰ ์ˆœํšŒ
39+
for c in range(right, left - 1, -1):
40+
output.append(matrix[bottom][c])
41+
bottom -= 1
42+
43+
# ์™ผ์ชฝ ์—ด ์ˆœํšŒ
44+
for r in range(bottom, top - 1, -1):
45+
output.append(matrix[r][left])
46+
left += 1
47+
48+
return output
49+
50+
# 2๊ฐœ์˜ ํฌ์ธํ„ฐ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ํ’€์ด
51+
"""
52+
- ์œ„์ชฝ ํ–‰์„ ์ˆœํšŒํ•œ ํ›„, ์—ด ์ธ๋ฑ์Šค๋ฅผ 1์”ฉ ์ฆ๊ฐ€
53+
- ์˜ค๋ฅธ์ชฝ ์—ด์„ ์ˆœํšŒํ•œ ํ›„, ํ–‰ ์ธ๋ฑ์Šค๋ฅผ 1์”ฉ ์ฆ๊ฐ€
54+
- ์•„๋ž˜์ชฝ ํ–‰์„ ์ˆœํšŒํ•œ ํ›„, ์—ด ์ธ๋ฑ์Šค๋ฅผ 1์”ฉ ๊ฐ์†Œ
55+
- ์™ผ์ชฝ ์—ด์„ ์ˆœํšŒํ•œ ํ›„, ํ–‰ ์ธ๋ฑ์Šค๋ฅผ 1์”ฉ ๊ฐ์†Œ
56+
57+
์ธ๋ฑ์Šค
58+
์‹œ์ž‘: (0, 0) => (ํ–‰, ์—ด)
59+
60+
ํƒˆ์ถœ ์กฐ๊ฑด
61+
1. ์œ„์ชฝ ํ–‰ ์ˆœํšŒ๋ฅผ ๋งˆ์น˜๊ณ  ์ƒ๋‹จ ์ธ๋ฑ์Šค๊ฐ€ ํ•˜๋‹จ ์ธ๋ฑ์Šค๋ณด๋‹ค ์ปค์ง€๋ฉด
62+
2. ์˜ค๋ฅธ์ชฝ ์—ด ์ˆœํšŒ๋ฅผ ๋งˆ์น˜๊ณ , ์šฐ์ธก ์ธ๋ฑ์Šค๊ฐ€ ์ขŒ์ธก ์ธ๋ฑ์Šค๋ณด๋‹ค ์ž‘์•„์ง€๋ฉด
63+
"""
64+
65+
class Solution:
66+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
67+
n_rows, n_cols = len(matrix), len(matrix[0])
68+
row, col = 0, -1
69+
direction = 1
70+
71+
output = []
72+
73+
# ๋‚จ์•„์žˆ๋Š” ์—ด๊ณผ ํ–‰์˜ ๊ฐœ์ˆ˜๊ฐ€ 0 ๋ณด๋‹ค ํฐ ๋™์•ˆ
74+
while 0 < n_rows and 0 < n_cols:
75+
for _ in range(n_cols):
76+
col += direction
77+
output.append(matrix[row][col])
78+
n_rows -= 1
79+
80+
for _ in range(n_rows):
81+
row += direction
82+
output.append(matrix[row][col])
83+
n_cols -= 1
84+
85+
direction *= -1
86+
87+
return output
88+

0 commit comments

Comments
ย (0)