#K92907. Counting Connected Islands
Counting Connected Islands
Counting Connected Islands
You are given an undirected graph with N nodes and M edges. The nodes are labeled from 1 to N. Two nodes are in the same island if there is a path between them. Your task is to determine the number of connected components (called islands) in the graph for each given test case.
More formally, let \(G(V, E)\) be an undirected graph where \(V = \{1, 2, \dots, N\}\) and \(E\) is a set of unordered pairs. An island is defined as a maximal subset \(I \subseteq V\) such that for any two nodes \(u,v \in I\), there exists a sequence \(u = x_0, x_1, \dots, x_k = v\) with each consecutive pair \((x_i, x_{i+1}) \in E\).
Your solution should read input from standard input (stdin) and output the result to standard output (stdout).
inputFormat
The input consists of multiple test cases. The first line contains an integer \(T\) specifying the number of test cases. Each test case is described as follows:
- The first line contains two integers \(N\) and \(M\) representing the number of nodes and the number of edges respectively.
- The next \(M\) lines each contain two space-separated integers \(u\) and \(v\) denoting an undirected edge between nodes \(u\) and \(v\).
It is guaranteed that \(1 \leq u, v \leq N\).
outputFormat
For each test case, print a single integer on a new line representing the number of connected components (islands) in the graph.
## sample2
5 3
1 2
2 3
4 5
4 0
2
4
</p>