You are given an undirected graph with n vertices labelled 0..n-1 and m edges. You may add new edges between any pair of vertices.
Report the minimum number of edges you must add so that the entire graph becomes connected (every vertex reachable from every other). If the graph is already connected the answer is 0.
Line 1: two integers n and m.
The next m lines each contain two integers u v, an undirected edge.
A single integer: the minimum number of extra edges required.
Example 1
Input
4 2 0 1 2 3
Expected
1
Explanation
There are two components {0,1} and {2,3}. One extra edge joins them, so the answer is 1.
Example 2
Input
4 3 0 1 1 2 2 3
Expected
0
Explanation
All four vertices already form one component, so no extra edges are needed. Answer is 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →