【数据结构与算法】之连通网络的操作次数的算法

一、题目要求
  • 用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b。
  • 网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。
  • 给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。
  • 示例一:
    在这里插入图片描述
	输入:n = 4, connections = [[0,1],[0,2],[1,2]]
	输出:1
	解释:拔下计算机 12 之间的线缆,并将它插到计算机 13 上。
  • 示例二:
    在这里插入图片描述
	输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
	输出:2
  • 示例三:
	输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
	输出:-1
	解释:线缆数量不足。
  • 示例四:
	输入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
	输出:0
  • 提示:
    • 1 <= n <= 10^5
    • 1 <= connections.length <= min(n*(n-1)/2, 10^5)
    • connections[i].length == 2
    • 0 <= connections[i][0], connections[i][1] < n
    • connections[i][0] != connections[i][1]
    • 没有重复的连接。
    • 两台计算机不会通过多条线缆连接。
二、算法思路
三、示例算法
  • Swift 示例
class Solution {
    
    
    class DSU {
    
    
        private var parent: [Int]
        private var compomentsCount: Int
        init(_ size: Int) {
    
    
            parent = Array<Int>(0...size)
            compomentsCount = size
        }
        func find(_ node: Int) -> Int {
    
    
            var current = node
            while parent[current] != current {
    
    
                current = parent[current]
            }
            var temp = node
            while parent[temp] != current {
    
    
                (temp,parent[temp]) = (parent[temp],current)
            }
            return current
        }
        func join(_ first: Int, _ second: Int)  {
    
    
            let firstRoot = find(find(first))
            let secondRoot = find(second)
            guard firstRoot != secondRoot else {
    
    
                return
            }
            compomentsCount -= 1
            parent[firstRoot] = secondRoot
        }
        func getCompomentsCount() -> Int {
    
    
            return compomentsCount
        }
    }
    func makeConnected(_ n: Int, _ connections: [[Int]]) -> Int {
    
    
        guard connections.count >= n - 1 else {
    
    
            return -1
        }
        let dsu = DSU(n)
        connections.forEach {
    
    
           dsu.join($0[0], $0[1])
        }
        return dsu.getCompomentsCount() - 1
    }
 }

猜你喜欢

转载自blog.csdn.net/Forever_wj/article/details/109267294