Clean-dfs-python
We have to find no. of connected components in a undirected graph\n\nimport collections\nclass Solution:\n    def makeConnected(self, n: int, connections: List[
**We have to find no. of connected components in a undirected graph**\n```\nimport collections\nclass Solution:\n    def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n        if len(connections)<n-1: # this is a edge condi. to connect n components we need min n-1 cables. \n            return -1\n        \n        \n        d=collections.defaultdict(list) # converting given list to adjacency list as it will help us to run dfs function.\n        for i ,j in connections:\n            d[i].append(j)\n            d[j].append(i)\n        \n        \n        visited=set()    # this will track the visited vertex\n        numofconnected=0 # this will track the no. of separate  components\n        \n        \n        def dfs(root):\n            visited.add(root)\n            for j in d[root]:# traversing each neighbour vertex of root and visit them in one go and add them to visited\n                if j not in visited:\n                    dfs(j)\n        \n        \n        for i in range(n): # running loop to track how many vertex we can visit through i \n            if i not in visited:\n                numofconnected+=1# as this is not visited so this will be the start of a new separate component .\n                dfs(i)\n        return numofconnected-1 # to connect n separate components we require min n-1 cables .\n        \n```\n![image](https://assets.leetcode.com/users/images/6f011696-9d14-43cb-9ea4-4d4ab3d74369_1622366404.3161256.png)\n
['Depth-First Search', 'Python']