Topics

# Blueprint

Moderate
0/80
Average time to solve is 20m
Contributed by
0 upvote

## Problem statement

Sam is updating the blueprint of a city. The original blueprint of the city consists of ‘N’ buildings numbered from 0 to ‘N’-1 which are connected by ‘M’ roads, ‘CONNECTIONS’ forming a network where CONNECTIONS[i] = [‘Ai’,’Bi’] represents a road between buildings ‘Ai’ and ‘Bi’.

Any building can be reached from any other building directly or indirectly connected through a series of roads.

There could be some buildings in the original blueprint of the city which are not connected with some other buildings directly or indirectly. Sam wants to update the blueprint of the city by removing some roads which directly connected any two buildings and adding a road between two disconnected buildings to make them connected.

Return the minimum number of times Sam needs to perform the changes such that all the buildings can be reached from any other building through a series of roads. If it is not possible, Return -1.

Example:
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.
Detailed explanation ( Input/output format, Notes, Images )
Constraints :
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
Sample Input 1 :
2
5 4
0 1
1 2
2 3
0 2
4 2
0 1
0 3
Sample Output 1 :
1
-1
Explanation Of Sample Input 1 :
Test 1:
Remove road between buildings 0 and 3, and add a road between building 0 and 4 , or 1     and 4 ,or 2 and 4 or 3 and 4.

Test 2:
There are not enough roads to connect all the building in the city, so return -1.
Sample Input 2 :
2
3 2
0 1
1 2
5 4
0 1
1 2
3 4
0 2
Sample Output 2 :
0
1
Console