> For the complete documentation index, see [llms.txt](https://shangan.gitbook.io/gong-kai-ke/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shangan.gitbook.io/gong-kai-ke/di-er-zhang-bfs/ke-hou-lian-xi/untitled-3.md).

# Number of Operations to Make Network Connected

![](https://gblobscdn.gitbook.com/assets%2F-MQQ_aKuDz0ArQY9xrTi%2F-MQQ_hCHEF_NfTLb7c5f%2F-MQQhK6lAaBSDTrKohkL%2FWechatIMG22.png?alt=media\&token=90bc890e-7a68-4f04-84cc-c23bbda959bd)

```java
/*
 本算法答案由上岸科技提供。
 上岸科技是一个专致力于高效培养北美留学生拥有实际面试能力的团体。
 我们采用小班化线上，线下教学让学生更快，更好的学习到想要的知识。
 团队主要由一群怀揣情怀于美国高校毕业的一线IT公司工程师构成。
 我们坚信对于求职者算法并不是全部，合理的技巧加上适当的算法培训能够大大的提升求职成功概率也能大大减少刷题的痛苦。
 正如我们的信仰：我们教的是如何上岸而不仅是算法。
 更多信息请关注官网：https://www.shanganonline.com/
*/
class Solution {
    public int makeConnected(int n, int[][] connections) {
        List<Integer>[] g = new ArrayList[n];
        for(int i = 0; i < n; i++) {
            g[i] = new ArrayList<>();
        }
        
        for(int[] e: connections) {
            g[e[0]].add(e[1]);
            g[e[1]].add(e[0]);
        }
        
        int numComponents = bfs(g, n);
        
        return connections.length >= n - 1 ? numComponents - 1 : -1;
    }
    
    private int bfs(List<Integer>[] g, int n) {
        int numComponents = 0;
        boolean[] visited = new boolean[n];
        for(int i = 0; i < n; i++) {
            if(visited[i]) {
                continue;
            }
            numComponents++;
            visited[i] = true;
            Queue<Integer> queue = new ArrayDeque<>();
            queue.add(i);
            
            while(!queue.isEmpty()) {
                int computer = queue.poll();
                for(int neighbor : g[computer]) {
                    if(!visited[neighbor]) {
                        visited[neighbor] = true;
                        queue.add(neighbor);
                    }
                }
            }
        }
        return numComponents;
    }
}
```

![](https://gblobscdn.gitbook.com/assets%2F-MQQ_aKuDz0ArQY9xrTi%2F-MQQ_hCHEF_NfTLb7c5f%2F-MQQhNaEDp_XdzFm0Ypp%2FWechatIMG23.png?alt=media\&token=0eec3fd8-70e7-4ac4-93e9-6cec19015bdb)
