Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Blueprint
MEDIUM
20 mins
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Blueprint

Contributed by
imObscure
Medium
yellow-spark
0/80
Avg time to solve 20 mins
Success Rate 75 %
Share
0 upvotes

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, Constraints, Images )
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
Reset Code
Full screen
Auto
copy-code
Console