#K48422. Counting Connected Components
Counting Connected Components
Counting Connected Components
You are given an undirected graph with N nodes and M edges. The nodes are labeled 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 in which every pair of nodes is connected directly or indirectly by edges.
The graph is provided via standard input and the answer should be output to standard output. It is recommended to use either Depth-First Search (DFS) or Union-Find (Disjoint Set Union) techniques to solve the problem.
inputFormat
The first line contains two space-separated integers N and M, representing the number of nodes and edges respectively. Each of the next M lines contains two space-separated integers u and v, describing an undirected edge between nodes u and v.
outputFormat
Output a single integer that denotes the number of connected components in the graph.## sample
5 3
1 2
2 3
4 5
2