↓快轉到主要內容
  1. LeetCode/

LeetCode 463: Island Perimeter

·1 分鐘· ·
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-24

  • 提交紀錄:Runtime Error ×6 → Wrong Answer ×3 → Runtime Error → Accepted → Runtime Error → Accepted ×2

解題思路
#

不用 DFS(BFS 模板二)。每格陸地有 4 條邊;兩格相鄰時共用的那條邊兩邊都不算,周長少 2。每格只檢查上方和左方,每對相鄰的格子就只會扣一次。

我的嘗試
#

這題 2022-08 錯了 11 次:

  • 前幾版邊界沒檢查,grid[row - 1] 在第一列時繞到最後一列,或者 row + 1 超出範圍。
  • 接下來兩版檢查了對角線(grid[row + 1][s + 1]、grid[row - 1][s - 1]),每個相鄰只扣 1:第一版沒檢查邊界,單獨一格 [[1]] 讀到 grid[-1][-1](自己)回傳 2;第二版補上邊界後,[[1, 1]] 回傳 8,答案 6。
  • 2024 年重寫成「每格 +4、跟上方左方相鄰各 -2」才 AC。

正確解法
#

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        res = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]:
                    res += 4
                    if i and grid[i - 1][j]:
                        res -= 2
                    if j and grid[i][j - 1]:
                        res -= 2
        return res

複雜度
#

時間 O(mn),空間 O(1)。

要特別避免的錯誤
#

  • 相鄰只看上下左右,不看對角線。
  • 每對相鄰扣 2,只檢查上方和左方避免重複。
  • grid[i - 1] 在 i = 0 時是最後一列,要先檢查 i > 0。

面試口說整理
#

每格陸地有四條邊,跟另一格陸地相鄰時共用的邊兩邊都不算,周長少二。我每格只看上方和左方,避免重複扣。時間 O(mn)、空間 O(1)。

相關文章

LeetCode 404: Sum of Left Leaves
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 解題筆記:DFS 時告訴小孩自己是不是左小孩,只有「是左小孩而且是葉子」才加
LeetCode 226: Invert Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 解題筆記:每個節點交換左右小孩;用同時指定,避免先改掉的那邊被拿來用
LeetCode 111: Minimum Depth of Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 解題筆記:最小深度要到葉子才算;只有一邊有小孩時不能拿空的那邊(深度 0)當最小值
LeetCode 112: Path Sum
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 解題筆記:往下走時把 targetSum 減掉目前的值,到葉子時剛好是 0(或等於葉子的值)就成立
LeetCode 100: Same Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 解題筆記:兩邊都是空的才相同;一邊空一邊不空就不同;都不空時比值再遞迴比左右
LeetCode 101: Symmetric Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 101 解題筆記:左子樹跟右子樹互為鏡像:外側跟外側比、內側跟內側比;比的是值,不是節點本身