Python 3 dfs easy to understand
\nclass Solution:\n    def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n# \u6392\u9664\u8FB9\u4E0D\u591F\u7684\u60C5\u51B5\n        if len
```\nclass Solution:\n    def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n# \u6392\u9664\u8FB9\u4E0D\u591F\u7684\u60C5\u51B5\n        if len(connections) < n - 1:\n            return -1\n        self.visited = set()\n \n#\u5EFA\u56FE\n        self.graph = [[] for _ in range(n)]\n        \n        count = 0\n        for connection in connections:\n            self.graph[connection[0]].append(connection[1])\n            self.graph[connection[1]].append(connection[0])\n  #\u9010\u4E2Anode\u6392\u67E5\uFF0C\u627E\u51FA\u8054\u901A\u5B50\u56FE\u4E2A\u6570\n        for i in range(n):\n            if i not in self.visited:\n                self.dfs(i)\n                count += 1\n        return count - 1\n            \n    #\u7528dfs\u6765\u627E\u8054\u901A\u5B50\u56FE\n    def dfs(self, i):\n        self.visited.add(i)\n        \n        for next_node in self.graph[i]:\n            if next_node not in self.visited:\n                self.dfs(next_node)\n\n```
[]