Input: ‘N’ = 5 , ‘M’ = 4 , 'CONNECTIONS' = [[0,1],[1,2],[2,3],[0,3]]
Output: 1
Explanation:
Remove the road between buildings 0 and 3, and add a road between buildings 0 and 4 , or 1 and 4 ,or 2 and 4 or 3 and 4.
The first line of the input contains an integer,’ T’ , denoting the number of test cases.
The first line of each test case contains two integers, 'N’ and ‘M’, denoting the number of buildings and number of connections..
The next ‘M’ lines of each test case contains pair of two integers, denoting the road between buildings.
Return an integer, denoting the minimum changes Sam needs to perform in the blueprint.
1 <= T <= 10
1 <= N <= 100000
1 <= M <= min(N x (N-1)/2 , 100000)
CONNECTIONS[i].length == 2
0 <= Ai,Bi < N
Ai != Bi
There are no repeated connections.
No two buildings are connected by more than one road.
Time Limit: 1 sec
The solution to the problem lies in counting the number of connected components.
We will make an adjacency list for undirected graph ‘adj’ using the ‘CONNECTIONS’, then if the number of roads is less than ‘N’-1, then the answer is not possible so return -1.
Now make a visited array, we run a loop for all buildings and if the current building is not marked in the visited array we will run a DFS for this building the mark all the connected buildings, and similarly, we will store the number of times we need to run a DFS in a counter, which is nothing but the number of connected components.
The DFS part can be implemented recursively or iteratively using a stack.
The solution to the problem lies in counting the number of connected components.
If the number of roads is less than ‘N’-1, then the answer is not possible so return -1.
Now we will make a data structure, Disjoint Set Union using which we will find the number of connected components, ‘counter’ and return counter-1.
The DSU part (Union by Size) can be implemented following the steps below.