全站文章索引 📚📚📚

展開全部 | 收合全部

全站文章索引 📚📚📚

展開全部 | 收合全部

【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

要處理的條件有:

  1. x, y 邊界
  2. 有沒有 visited

而結束的判斷條件為:

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

Reference

Howard Weng
Howard Weng

我是 Howard Weng,很多人叫我嗡嗡。這個網站放了我的各種筆記。希望這些筆記也能順便幫助到有需要的人們!如果文章有幫助到你的話,歡迎幫我點讚哦!
另外,因為定位是「個人的隨手筆記」,有些文章內容「⚠️可能我理解有誤⚠️」或「🥱只寫到一半😴」,如果有發現這樣的情況,歡迎在該文章的最下面留言提醒我!我會儘快修正或補上!感謝大家的建議與幫忙,讓網站能變得更好🙏

文章: 817

2 則留言

★留個言吧!內容有誤或想要補充也歡迎與我討論!