본문 바로가기

LEETCODE

#54. Spiral Matrix

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        result = []
        top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1

        while top <= bottom and left <= right:
            for i in range(left, right + 1):
                result.append(matrix[top][i])
            top += 1

            for i in range(top, bottom + 1):
                result.append(matrix[i][right])
            right -= 1

            if top <= bottom:
                for i in range(right, left - 1, -1):
                    result.append(matrix[bottom][i])
                bottom -= 1

            if left <= right:
                for i in range(bottom, top - 1, -1):
                    result.append(matrix[i][left])
                left += 1

        return result

'LEETCODE' 카테고리의 다른 글

up_stage interview prep  (0) 2023.11.10
#62. Unique Paths  (1) 2023.11.01
#55. Jump Game  (0) 2023.11.01
#53. Maximum Subarray  (0) 2023.11.01
#34. Find First and Last Position of Element in Sorted Array  (0) 2023.11.01