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

LeetCode 1319: Number of Operations to Make Network Connected

·1 分鐘· ·
LeetCode Medium Union-Find
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試: 2025-05-06

  • 總花費時間:10:00.00

解題思路
#

若要讓所有電腦互相連接,最少需要 n - 1 條線,其中 n 是電腦數量。
如果現有的線(m 條)少於 n - 1,則不可能讓所有電腦都連起來。
因此,我們可以使用並查集(Union Find)來把所有已經連接的電腦合併成一組。
合併完成後,我們就可以知道總共有多少個獨立的群組,也就知道還需要多少額外的線來連接這些群組。

在 union 的過程中,如果發現兩台電腦已經在同一個群組,那就代表這條線是多餘的,我們可以把它記錄下來作為可移動的線。
最後,我們只需要判斷多餘的線是否足夠連接剩下的獨立群組(也就是 獨立群組數量 - 1),如果夠就回傳需要的操作次數,否則回傳 -1。

解法
#

class Solution:
    def makeConnected(self, n: int, connections: List[List[int]]) -> int:
        parent = [i for i in range(n)]
        ranking = [0 for _ in range(n)]
        extra = 0
        needed = 0

        def find(n):
            if parent[n] != n:
                parent[n] = find(parent[n])
            return parent[n]

        def union(x, y):
            nonlocal extra
            root_x = find(x)
            root_y = find(y)

            if root_x == root_y:
                extra += 1
                return

            if ranking[root_x] > ranking[root_y]:
                parent[root_y] = parent[root_x]
                ranking[root_x] += ranking[root_y]
            else:
                parent[root_x] = parent[root_y]
                ranking[root_y] += ranking[root_x]

        for x, y in connections:
            union(x, y)

        for i in range(n):
            if parent[i] == i:
                needed += 1
        
        return needed - 1 if (needed - 1) <= extra else -1

收穫
#

遇到的問題
#

相關文章

LeetCode 1202: Smallest String With Swaps
·1 分鐘
LeetCode Medium Union-Find
LeetCode 解題紀錄
LeetCode 547: Number of Provinces
·2 分鐘
LeetCode Medium Union-Find Dfs
LeetCode 解題紀錄
LeetCode 684: Redundant Connection
·1 分鐘
LeetCode Daily Medium Union-Find
LeetCode 解題紀錄
LeetCode 3493: Properties Graph
·1 分鐘
LeetCode Medium Graph Dfs Union-Find Hash-Map
LeetCode 3493 解題筆記:先把每列轉成 set,兩兩比較交集大小建邊,再數連通塊
LeetCode 695: Max Area of Island
·1 分鐘
LeetCode Medium Array Depth-First-Search Breadth-First-Search Union-Find
LeetCode 695 解題筆記:每遇到一個沒走過的 1 就 DFS 整座島,數格子數,取最大值;格子是整數 1,不是字串
LeetCode 128: Longest Consecutive Sequence
·1 分鐘
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 解題筆記:放進 set,只從「x - 1 不在 set 裡」的數開始往上數,每個數最多被看兩次,O(n)