Number of Connected Components

Practice this coding question on Coding Gurukul.

Problem statement

A utility company tracks stations joined by undirected service links. A maintenance crew can move within any connected group, but needs a separate assignment for each group that cannot be reached from the others. Your task Count the connected components of the undirected graph, including isolated vertices. Important details Connections are transitive: stations linked by a multi-edge route belong to one component even without a direct edge. Cycles do not create extra components. Visit all n stations, not only those that appear in the edge list. Worked example With five vertices and links 0-1 and 1-2, the components are {0, 1, 2}, {3} and {4}. The answer is 3.

Input format

First line: n m. Next m lines: endpoints u v of undirected edges. Vertices are numbered 0 through n-1.

Output format

Print the component count.

Constraints

1 <= n <= 2000; 0 <= m <= 10000; endpoints are valid, with no self-loops or repeated edges.

Sample input

5 2
0 1
1 2

Sample output

3

Sign in to run or submit a solution in C++, Java or Python.