#K90777. Count Connected Components
Count Connected Components
Count Connected Components
You are given an undirected graph with N nodes and E edges. The nodes are numbered from 1 to N.
Your task is to determine the number of connected components in the graph.
A connected component is a set of nodes such that there is a path between any two nodes in the set.
Note: If there are no edges (i.e. E = 0), each node is considered as a separate connected component.
The solution should read input from stdin
and write the result to stdout
.
The problem can be formally stated using the formula below:
\( \text{Number of Connected Components} = \#\{\text{maximal sets of nodes } S: \forall u, v \in S, \text{there exists a path from } u \text{ to } v\} \)
inputFormat
The first line contains two integers N and E, representing the number of nodes and edges respectively.
Each of the following E lines contains two space-separated integers u and v, indicating that there is an undirected edge between node u and node v.
Constraints: 1 ≤ N ≤ 105, 0 ≤ E ≤ 105.
outputFormat
Output a single integer - the number of connected components in the given graph.
## sample6 5
1 2
2 3
3 1
4 5
5 6
2