391. Number of operations to make network connected

Given a graph with n vertices and m edges. The graph is represented by an array Edges, where Edge[i] = [a, b] indicates an edge between vertices a and b. One edge can be removed from anywhere and added between any two vertices in one operation. Find the minimum number of operations that will be required to make the graph connected. If it is not possible to make the graph connected, return -1.

Example 1:

Input : n = 4, Edge =[ [0, 1], [ 0, 2], [1, 2]]

Output: 1

Explanation: We need a minimum of 1 operation to make the two components connected. We can remove the edge (1,2) and add the edge between node 2 and node 3 like the following:

Example 2:

Input: n = 9, Edge = [[0,1],[0,2],[0,3],[1,2],[2,3],[4,5],[5,6],[7,8]]

Output: 2

Explanation: We need a minimum of 2 operations to make the two components connected. We can remove the edge (0,2) and add the edge between node 3 and node 4 and we can remove the edge (0,3) and add it between nodes 6 and 8 like the following:

Now Your Turn!

Pick the correct output for the given input

Input: n = 4, Edge =[[0, 1]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  •   1 <= n <= 104
  •   1 <= Edge.length <= 104
  •   Edge[i].length == 2

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution{
public:
int solve(int n, vector<vector<int>> &Edge){
}
};
 
Test Case

Input:

Edge
N