Notice
Recent Posts
Recent Comments
Link
오늘도 개발
19. Spiral Matrix 본문
문제
2차원 배열의 요소를 나선형 순으로 반환하라.

내가 생각한 해결 방식
실제로 나선형으로 순회하며 요소를 result 배열에 담는 방법.
[1, 2, 3, 4, 9, 8, 7, 4, 7]로 값을 잘못 저장하고,
list index out of range 오류가 나서 통과 못함.
def spiralOrder(matrix):
row, column = 0, 0
row_start, column_start = 0, 0
row_end, column_end = len(matrix) - 1, len(matrix[0]) - 1
result = []
while row_start != row_end or column_start != column_end:
while column <= column_end:
result.append(matrix[row][column])
column += 1
column -= 1
column_end -= 1
row += 1
while row <= row_end:
result.append(matrix[row][column])
row += 1
row -= 1
row_end -= 1
column -= 1
while column >= column_start:
result.append(matrix[row][column])
column -= 1
column += 1
column_start -= 1
row -= 1
while row >= row_start:
result.append(matrix[row][column])
row += 1
row -= 1
row_start += 1
column += 1
return result
해결 방식
슬라이싱과 pop() 메서드 활용.
result에 담은 요소는 삭제하면서 진행됨.
- if matrix and matrix[0]라는 조건을 주는 이유 :
if matrix라는 조건만 있으면 matrix가 [[7], [9], [6]]인 경우에 오류 발생.
두 번째 작업(오른쪽 끝줄을 없애는 작업)을 마치면 matrix가 [[], []]가 되기 때문에,
세 번째 작업(아랫줄을 pop하는 작업) 시 빈 배열에 pop을 적용할 수 없으므로 오류가 남.
def spiralOrder(matrix):
result = []
while matrix and matrix[0]:
if matrix[0]:
# 첫번째 row를 result에 넣고 삭제
result += matrix.pop(0)
if matrix and matrix[0]:
# 각 row의 맨 마지막 요소를 result에 넣고 삭제
for row in matrix:
result.append(row.pop())
if matrix and matrix[0]:
# # 마지막 row를 pop한 결과를 반대 순서로 만들고 result에 넣음
result += matrix.pop()[::-1]
if matrix and matrix[0]:
# matrix를 거꾸로 뒤집고
for row in matrix[::-1]:
# 맨 앞 요소를 result에 넣고 삭제
result.append(row.pop(0))
return result'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글
| 21. Add Binary (0) | 2022.10.11 |
|---|---|
| 20. Pascal's Triangle (1) | 2022.09.23 |
| 17. Plus One (0) | 2022.09.16 |
| 16. Largest Number At Least Twice of Others (0) | 2022.09.14 |
| 15. Find Pivot Index(1991) (0) | 2022.09.13 |