java - easy to understand BFS solution (commented)
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n  public int makeConnected(int n, int[][] connections) {\n    LinkedList<Integer>[] g = new LinkedList[n];                 //create graph\n    for(int i = 0; i != n; ++i) g[i] = new LinkedList<>();\n\n    for(int[] c: connections){                                   //put in graph all components\n      g[c[0]].add(c[1]); \n      g[c[1]].add(c[0]);\n    }\n\n    int[] vis = new int[n];                                      //visited for BFS\n    int free_edges = 0, components = 0;                          //will count in graph all components and all edges for it\n    for(int i = 0; i != n; ++i)\n      if(vis[i] == 0){                                //we have new component\n        int edges = 0, vertexes = 0;                  //for all vertexes and edges in it\n        \n        LinkedList<Integer> q = new LinkedList<>();   //BFS for component\n        q.add(i);\n        while(!q.isEmpty()){\n          int node = q.poll();\n          if(vis[node] == 1) continue;\n          vis[node] = 1;\n          ++vertexes;\n          edges += g[node].size();\n\n          for(int neib: g[node])\n            if(vis[neib] == 0) q.add(neib);\n        }\n\n        free_edges += (edges>>1) - vertexes + 1;      //fetch all free edges (convert component into DAG)\n        ++components;\n      }\n\n    if(free_edges < (components - 1) ) return -1;     //check number of components and free edges\n    return components - 1;\n  }\n}\n```
['Java']