Minimum Operations to Connect a Graph

You are given a graph with 'N' vertices labeled from 1 to 'N' and 'M' edges. In one operation, you can shift an edge from being between two directly connected vertices to between a pair of disconnected vertices, making them directly connected. The task is to determine the minimum number of such operations required to make the entire graph connected. If the graph cannot be connected, return -1.

Example:

Input:
N = 4, M = 3
Edges = [(1,2), (2,3), (1,3)]
Output:
1
Explanation:

You can shift the edge from (1,3) to (1,4) to connect the graph. There are multiple ways to make the graph connected. In this scenario, only one operation is needed.

Input:

The first line contains a single integer 'T', the number of test cases.
The first line for each test case contains two integers 'N' and 'M', representing the number of vertices and edges.
Each of the next 'M' lines contains two integers denoting the vertices connected by an edge.

Output:

For each test case, print a single integer indicating the minimum number of operations required to connect the graph. If the graph cannot be connected, print -1.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 10000
  • 1 <= M <= 10000
  • 1 <= U[i], V[i] <= N

Where 'T' is the number of test cases, 'N' is the number of vertices, 'M' is the number of edges, and 'U[i]' and 'V[i]' are vertices of the i-th edge.

Time Limit: 1 sec.

Note:

You do not need to handle any input or output processes, just implement the given function.

Be the first one to answer
Add answer anonymously...
Uber Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter