Skip to content

Commit e34f9af

Browse files
committed
add spiralOrder function to return elements of a matrix in spiral order
1 parent b2912ea commit e34f9af

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

spiral-matrix/gcount85.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
# Approach
3+
상하좌우 경계값을 설정하고 matrix을 순회하며 경계값을 줄여나갑니다.
4+
5+
# Complexity
6+
matrix 크기의 가로를 M, 세로를 N이라고 할 때
7+
- Time complexity: O(M*N)
8+
- Space complexity: O(M*N)
9+
"""
10+
11+
12+
class Solution:
13+
def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
14+
start_row, start_col = 0, 0
15+
end_row, end_col = len(matrix) - 1, len(matrix[0]) - 1
16+
output = []
17+
18+
while start_row <= end_row and start_col <= end_col:
19+
# 좌->우
20+
for col in range(start_col, end_col + 1):
21+
output.append(matrix[start_row][col])
22+
start_row += 1
23+
24+
# 상->하
25+
for row in range(start_row, end_row + 1):
26+
output.append(matrix[row][end_col])
27+
end_col -= 1
28+
29+
# 우->좌
30+
if start_row <= end_row:
31+
for col in range(end_col, start_col - 1, -1):
32+
output.append(matrix[end_row][col])
33+
end_row -= 1
34+
35+
# 하->상
36+
if start_col <= end_col:
37+
for row in range(end_row, start_row - 1, -1):
38+
output.append(matrix[row][start_col])
39+
start_col += 1
40+
41+
return output

0 commit comments

Comments
 (0)