Problem statement
An undirected graph has N vertices numbered from 1 to N and M edges. A connected component is a maximal group of vertices in which every vertex can reach every other vertex. Determine the number of connected components. An isolated vertex is a component by itself. Self-loops and repeated edges are allowed and do not change connectivity.
Input format
The first line contains N and M. The next M lines contain U and V, describing an undirected edge.
Output format
Print one integer: the number of connected components.
Constraints
- 1 ≤ N ≤ 100000
- 0 ≤ M ≤ 200000
- 1 ≤ U, V ≤ N
Sample input
6 3 1 2 2 3 4 5
Sample output
3
Sample explanation
The components are {1, 2, 3}, {4, 5}, and {6}. Start a traversal at each vertex that has not already been visited.
Need a hint?
A traversal visits exactly one component. Remember to check every vertex, including isolated vertices. An iterative DFS avoids call-stack overflow on long chains.