C++✅✅ Easy solution✅ ✅DFS🔥
Har Har Mahadev\u2764\uFE0F\uD83D\uDD49\uFE0F\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nCheck number of wire we have if numb
Har Har Mahadev\u2764\uFE0F\uD83D\uDD49\uFE0F\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck number of wire we have if number of wire is less than connections than it\'s not possible to connect all devices\n\nCheck number of components , after counting number of components we can return ans-1 (Because we can connect n devices with n-1 wire)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCollect data in adjacency list and after that run DFS don\'t forget to maintain a visited array to not visit one node again and again\n\nStart from \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(V+E), where V is the number of vertices and E is the number of edges in the graph.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n The space complexity of the DFS algorithm is O(V).\nAnd we are making adjacency list is O(V+E)\n\n\n# Code\n```\nclass Solution {\n    void dfs(vector<int> adj[], vector<bool> &visited, int src)\n    {\n        visited[src] = true;\n        for(int i : adj[src]){\n            if(!visited[i]){\n                dfs(adj, visited, i);\n            }\n        }\n    }\npublic:\n    int makeConnected(int n, vector<vector<int>>& arr) {\n        int len = arr.size();\n        if(len<n-1) return -1;\n         vector<int> adj[n];\n        for(auto v : arr)\n        {\n            adj[v[0]].push_back(v[1]);\n            adj[v[1]].push_back(v[0]);\n        }\n        vector<bool> visited(n, false);\n        int ans = 0;\n        for(int i=0; i<n; i++)\n        if(!visited[i])\n        {\n            dfs(adj, visited, i);\n            ans++;\n        }\n        return ans - 1;\n    }\n};\n\n\n\n\n```\nI hope you guys understand the solution , if there is any confusion or any improvements in the solution please inform me.\n\nJai Shree Ram \uD83D\uDEA9\uD83D\uDE4F.\n\n\n
['Depth-First Search', 'Graph', 'C++']