Number of Islands II 解題教學:3 種解法完整比較|LeetCode 305 Best Practice

Number of Islands II 解題教學示意圖|LeetCode 305

本文完整拆解 LeetCode 305 Number of Islands II 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Number of Islands II 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0‘s represent water and 1‘s represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0‘s).

We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation.

Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
Output: [1,1,2,3]
Explanation:
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.

Example 2:

Input: m = 1, n = 1, positions = [[0,0]]
Output: [1]

Constraints:

  • 1 <= m, n, positions.length <= 104
  • 1 <= m * n <= 104
  • positions[i].length == 2
  • 0 <= ri < m
  • 0 <= ci < n

Follow up: Could you solve it in time complexity O(k log(mn)), where k == positions.length?

Python

				
					# time complexity: O(m*n)
# space complexity: O(m*n)
from typing import List


class Solution:
    class UnionFind:
        def __init__(self, size):
            self.rep = [i for i in range(size)]
            self.rank = [0] * size
            self.count = 0

        def find(self, node):
            if node != self.rep[node]:
                self.rep[node] = self.find(self.rep[node])
            return self.rep[node]

        def union(self, node1, node2):
            rep1 = self.find(node1)
            rep2 = self.find(node2)
            if rep1 != rep2:
                if self.rank[rep1] > self.rank[rep2]:
                    self.rep[rep2] = rep1
                elif self.rank[rep2] < self.rank[rep1]:
                    self.rep[rep1] = rep2
                else:
                    self.rep[rep2] = rep1
                    self.rank[rep1] += 1
                self.count -= 1

    def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
        uf = self.UnionFind(m * n)
        res = []
        land_map = set()

        for row, col in positions:
            if (row, col) in land_map:
                res.append(uf.count)
                continue

            land_map.add((row, col))
            uf.count += 1

            for i, j in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
                r, c = row + i, col + j
                if r < 0 or c < 0 or r >= m or c >= n:
                    continue
                if (r, c) in land_map:
                    uf.union(row * n + col, r * n + c)

            res.append(uf.count)

        return res


m = 3
n = 3
positions = [[0, 0], [0, 1], [1, 2], [2, 1]]
print(Solution().numIslands2(m, n, positions))
				
			

Number of Islands II 解題思路

這題是動態版的島嶼計數:每次加入一塊陸地後都要回報目前島嶼數。重跑 DFS 太慢,正解是並查集——新增一格時先把答案加一(自成一島),再檢查四個鄰居,每成功合併一次就把答案減一,因為兩座島合併成一座。

Number of Islands II 演算法步驟

  1. 用一維陣列模擬二維座標的並查集,初始全部標記為水。
  2. 每次加入座標 (r, c):若已是陸地就沿用上一個答案。
  3. 否則標記為陸地、count++,並初始化它的父節點指向自己。
  4. 檢查四個鄰居,若是陸地且 union 成功(原本不同集合)就 count–;把 count 記入答案陣列。

Number of Islands II 複雜度分析

項目複雜度
時間複雜度O(k α(m·n))
空間複雜度O(m·n)

k 是操作次數。每次操作最多做四次並查集合併,搭配路徑壓縮與按秩合併後幾乎是常數時間,整體為 O(k α(m·n))。父節點與秩陣列佔 O(m·n)。

Number of Islands II 的邊界情況與常見錯誤

  • 同一個座標可能被重複加入,要先判斷是否已是陸地,否則 count 會多加。
  • union 前要確認鄰居確實是陸地,水格不能參與合併。
  • 二維轉一維索引用 r * n + c,別把 m 和 n 弄反。
  • 一定要做路徑壓縮,否則最壞會退化成線性。

Number of Islands II 其他解法比較

解法時間空間說明
每次操作重跑一次 DFS 計數O(k·m·n)O(m·n)正確但太慢
維護島嶼集合並手動合併O(k·m·n)O(m·n)合併成本高
並查集動態合併O(k α(m·n))O(m·n)本文採用