【Leetcode】python - [54] Spiral Matrix 個人解法筆記

題目出處

54. Spiral Matrix

難度

medium

個人範例程式碼

MOVES = [
    (0, 1),
    (1, 0),
    (0, -1),
    (-1, 0)    
]
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []

        x, y = 0, 0
        direction = 0
        visited = {(0, 0)}
        ans = [matrix[0][0]]
        total_num = len(matrix) * len(matrix[0])
        while(len(ans) < total_num):
            next_x, next_y = x + MOVES[direction][0], y + MOVES[direction][1]
            if self.isvalid(next_x, next_y, matrix, visited):
                ans.append(matrix[next_x][next_y])
                visited.add((next_x, next_y))
                x, y = next_x, next_y
            else:
                direction = (direction + 1)%4

        return ans


    def isvalid(self, x, y, matrix, visited):
        r = len(matrix)
        c = len(matrix[0])
        return 0 <= x < r and 0 <= y < c and (x, y) not in visited

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

算法說明

螺旋狀的 traverse 矩陣,
記得設定好邊界條件,就可以處理

input handling

當沒有 matrix 時,return []

Boundary conditions

要處理的條件有:

    - x, y 邊界 - 有沒有 visited

而結束的判斷條件為:

while len(ans) < total_nums,
當得到全部的結果後,就會結束迴圈。

Reference