LeetCode1319. 连通网络的操作次数

1319. Number of Operations to Make Network Connected

There are n computers numbered from 0 to n-1 connected by ethernet cables connections forming a network where connections[i] = [a, b] represents a connection between computers a and b. Any computer can reach any other computer directly or indirectly through the network.

Given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it’s not possible, return -1.

Example 1:

img

Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.

Example 2:

img

Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2

Example 3:

Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Explanation: There are not enough cables.

Example 4:

Input: n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
Output: 0

Constraints:

  • 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]
  • There are no repeated connections.
  • No two computers are connected by more than one cable.

题目:用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 ab。网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。给你这个计算机网络的初始布线connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。

思路:统计联通的子网络的个数res,则使所有计算机都连通所需的线缆数为res-1。参考lee215

工程代码下载

class Solution {
public:
    int makeConnected(int n, vector<vector<int>>& connections) {
        // 统计每台计算机的出度
        vector<set<int>> node(n);
        for(auto vec : connections){
            node[vec[0]].insert(vec[1]);
            node[vec[1]].insert(vec[0]);
        }

        vector<bool> seen(n, false);

        // 至少需要n-1根线缆来联通n台计算机
        if(connections.size() < n-1)
            return -1;

        int res = 0;
        for(int i = 0; i < n; ++i)
            res += dfs(node, seen, i);

        return res - 1;
    }
private:
    int dfs(const vector<set<int>>& node, vector<bool>& seen, int i){
        if(seen[i])
            return 0;

        seen[i] = true;
        for(auto j : node[i])
            dfs(node, seen, j);

        return 1;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章