[LeetCode] 54. Spiral Matrix

김민우·2023년 5월 9일
0

알고리즘

목록 보기
185/189

- Problem

54. Spiral Matrix


- 내 풀이

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        DIRECTION = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        M, N = len(matrix), len(matrix[0])

        cur_dir = 0
        cur_y, cur_x = 0, 0

        spiral_order = []

        while len(spiral_order) < M * N:
            if matrix[cur_y][cur_x] is not None:
                spiral_order.append(matrix[cur_y][cur_x])
                matrix[cur_y][cur_x] = None
            
            ny, nx = cur_y + DIRECTION[cur_dir][0], cur_x + DIRECTION[cur_dir][1]
            if not (0 <= ny < M and 0 <= nx < N and matrix[ny][nx] is not None):
                cur_dir = (cur_dir + 1) % 4

            cur_y, cur_x = cur_y + DIRECTION[cur_dir][0], cur_x + DIRECTION[cur_dir][1]

        return spiral_order

- 결과

  • 시간 복잡도: O(MN)
  • 공간 복잡도: O(1)
profile
Pay it forward.

0개의 댓글