Detailed DFS explanation with C++ Code!
(Number of connected components-1 ) is the requied answer.\nJust think none of the computers are connected.Clearly n-1 is the minimum number of wires required t
(Number of connected components-1 ) is the requied answer.\nJust think none of the computers are connected.Clearly n-1 is the minimum number of wires required to connect them.\nNow visualise each of those computers as connected components.As once we reach one of the computers in the connected component we reach everything in that component.So, (Number of connected components-1 ) is the requied answer.\n\nNow twist is that to connect all computers you need n-1 wires.But so if total wires less than n-1 return -1.\n\nSee the code below for more clarity!.\n\n```\nclass Solution {\npublic:\n    void dfs(vector<vector<int>>& graph,vector<int>& visited,int i)\n    {\n        if(visited[i])\n            return;\n        visited[i]=1;\n        for(auto x:graph[i])\n        {\n            dfs(graph,visited,x);\n        }\n    }\n    int makeConnected(int n, vector<vector<int>>& connections) {\n        vector<vector<int>> graph(n);\n        for(auto& a:connections)\n        {\n            graph[a[0]].push_back(a[1]);\n            graph[a[1]].push_back(a[0]);\n        }\n        vector<int> visited(n);\n        int ctr=0;\n        for(int i=0;i<n;i++)\n        {\n            if(!visited[i])\n            {\n                dfs(graph,visited,i);\n                ctr++;\n            }\n        }\n        if(connections.size()>=n-1)\n            return ctr-1;\n        else\n            return -1;\n    }\n};\n```\nHope it helped!
[]