#K76567. Count Connected Components in an Undirected Graph

    ID: 34671 Type: Default 1000ms 256MiB

Count Connected Components in an Undirected Graph

Count Connected Components in an Undirected Graph

You are given an undirected graph with n nodes and m edges. The nodes are labeled from 1 to n. Each edge connects two nodes. Your task is to compute the number of connected components in the graph.

A connected component is a set of nodes where each node is reachable from any other node in the same set. Formally, if we denote the graph as \(G=(V,E)\) with \(V=\{1,2,\ldots,n\}\), you need to find the number of subsets \(C_1, C_2, \ldots, C_k\) such that:

\[ \bigcup_{i=1}^{k}C_i = V \quad \text{and} \quad C_i \cap C_j = \emptyset \text{ for } i \neq j \]

and for each \(C_i\), any two nodes are connected by some path in the graph.

You may use standard graph traversal techniques such as depth-first search or union-find to solve this problem.

inputFormat

The first line contains two integers n and m separated by a space, where n is the number of nodes and m is the number of edges in the graph.

The next m lines each contain two integers u and v representing an undirected edge connecting node u and node v.

It is guaranteed that \(1\leq u,v\leq n\).

outputFormat

Output a single integer indicating the number of connected components in the graph.

## sample
5 3
1 2
2 3
4 5
2