【leetcode】1319. 连通网络的操作次数(number-of-operations-to-make-network-connected)(BFS)[中等]

2023-05-16

链接

https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected/

耗时

解题:29 min
题解:7 min

题意

用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b。

网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。

给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。

思路

首先如果边的数量小于节点数量减一,则不能得到连通图,返回 -1。每有两个不连通的块则需要一次操作连接他们,所以答案即是连通块数量减一。

时间复杂度: O ( V + E ) O(V+E) O(V+E)

AC代码

class Solution {
public:
    int makeConnected(int n, vector<vector<int>>& connections) {
        int m = connections.size();
        if(m < n-1) return -1;
        vector<vector<int>> E(n);
        for(auto x : connections) {
            E[x[0]].push_back(x[1]);
            E[x[1]].push_back(x[0]);
        }
        vector<bool> vis(n, false);
        int cnt = 0;
        for(int i = 0; i < n; ++i) {
            if(vis[i]) continue;
            vis[i] = true;
            cnt++;
            queue<int> q;
            q.push(i);
            while(!q.empty()) {
                int now = q.front();
                q.pop();
                for(int j = 0; j < E[now].size(); ++j) {
                    int to = E[now][j];
                    if(vis[to]) continue;
                    vis[to] = true;
                    q.push(to);
                }
            }
        }
        return cnt-1;
    }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【leetcode】1319. 连通网络的操作次数(number-of-operations-to-make-network-connected)(BFS)[中等] 的相关文章

随机推荐