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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章