Easy to understand Java implementation using find disconnected components concept
To connect all vertices V you need atleast V-1 edges. If you don\'t have that there is no possible way to connect all vertices and simply return -1. Else find a
To connect all vertices **V** you need atleast **V-1** edges. If you don\'t have that there is no possible way to connect all vertices and simply return -1. Else find all disconnected components lets say N and to connect N disconnected components you will need **N-1** edges and simply return **N-1**.\nSolve - https://leetcode.com/problems/number-of-provinces/ to understand disconnected components.\n```\nclass Solution {\n    public int makeConnected(int n, int[][] connections) {\n        if(connections.length<n-1)\n            return -1;\n        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n        for(int i=0;i<n;i++)\n            adj.add(new ArrayList<>());\n        for(int[] edge : connections){\n            adj.get(edge[0]).add(edge[1]);\n            adj.get(edge[1]).add(edge[0]);\n        }\n        boolean[] visited = new boolean[n];\n        int count = 0;\n        for(int i=0;i<n;i++){\n            if(!visited[i]){\n                count++;\n                dfs(adj, i, visited);\n            }\n        }\n        return count-1;\n    }\n    void dfs(ArrayList<ArrayList<Integer>> adj, int node, boolean[] visited){\n        if(visited[node])\n            return;\n        visited[node] = true;\n        for(int i : adj.get(node)){\n            dfs(adj, i, visited);\n        }\n    }\n}\n```
[]