Skip to content

Commit 9d995c6

Browse files
committed
solve 1
1 parent 58d7639 commit 9d995c6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

spiral-matrix/pmjuu.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
시간복잡도: O(m * n) - 모든 행렬의 요소를 한 번씩 방문
3+
공간복잡도: O(1) - 추가 공간 없이 결과를 저장
4+
'''
5+
from typing import List
6+
7+
8+
class Solution:
9+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
10+
result = []
11+
top, bottom = 0, len(matrix) - 1
12+
left, right = 0, len(matrix[0]) - 1
13+
14+
while top <= bottom and left <= right:
15+
for col in range(left, right + 1):
16+
result.append(matrix[top][col])
17+
top += 1
18+
19+
for row in range(top, bottom + 1):
20+
result.append(matrix[row][right])
21+
right -= 1
22+
23+
if top <= bottom:
24+
for col in range(right, left - 1, -1):
25+
result.append(matrix[bottom][col])
26+
bottom -= 1
27+
28+
if left <= right:
29+
for row in range(bottom, top - 1, -1):
30+
result.append(matrix[row][left])
31+
left += 1
32+
33+
return result

0 commit comments

Comments
 (0)