LeetCode/Top Interview 150

54. Spiral Matrix

hyunkookim 2024. 11. 30. 16:33

54. Spiral Matrix

 

https://youtu.be/BJnMZNwUk1M?si=al69ISRZ14ay6XCH

 

from typing import List

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []  # 결과를 저장할 리스트
        left, right = 0, len(matrix[0])  # 왼쪽과 오른쪽 경계
        top, bottom = 0, len(matrix)  # 위쪽과 아래쪽 경계

        # 스파이럴 탐색은 왼쪽 < 오른쪽, 위쪽 < 아래쪽일 때까지 반복
        while left < right and top < bottom:
            # 1. 위쪽 행의 모든 값을 왼쪽에서 오른쪽으로 추가
            for i in range(left, right):
                res.append(matrix[top][i])
            top += 1  # 위쪽 경계를 아래로 한 칸 이동

            # 2. 오른쪽 열의 모든 값을 위에서 아래로 추가
            for i in range(top, bottom):
                res.append(matrix[i][right - 1])
            right -= 1  # 오른쪽 경계를 왼쪽으로 한 칸 이동

            # 3. 남은 영역이 유효한지 확인 (왼쪽 < 오른쪽, 위쪽 < 아래쪽)
            if not (left < right and top < bottom):
                break

            # 4. 아래쪽 행의 모든 값을 오른쪽에서 왼쪽으로 추가
            for i in range(right - 1, left - 1, -1):
                res.append(matrix[bottom - 1][i])
            bottom -= 1  # 아래쪽 경계를 위로 한 칸 이동

            # 5. 왼쪽 열의 모든 값을 아래에서 위로 추가
            for i in range(bottom - 1, top - 1, -1):
                res.append(matrix[i][left])
            left += 1  # 왼쪽 경계를 오른쪽으로 한 칸 이동

        return res  # 결과 반환

'LeetCode > Top Interview 150' 카테고리의 다른 글

383. Ransom Note  (0) 2024.11.30
48. Rotate Image  (0) 2024.11.30
36. Valid Sudoku  (0) 2024.11.30
76. Minimum Window Substring  (0) 2024.11.30
30. Substring with Concatenation of All Words  (0) 2024.11.29