A field engineer has set up n signal towers, numbered 1 to n. She has also laid m two-way wires between towers. Two towers can exchange a signal if there is a path of wires between them (possibly through other towers). A tower with no wire at all still forms its own cluster of size one.
Count the number of independent relay clusters.
Line 1: two integers n and m — the number of towers (1-indexed) and the number of wires.
Next m lines: two integers u v — a wire between tower u and tower v (undirected). The same pair may appear more than once, and a wire may connect a tower to itself; both cases should be handled without affecting the answer.
A single integer: the number of relay clusters.
Example 1
Input
5 2 1 2 2 3
Expected
3
Explanation
Towers 1-2-3 form one cluster; towers 4 and 5 are each their own cluster. Total: 3 clusters.
Example 2
Input
4 3 1 2 3 4 1 2
Expected
2
Explanation
The wire 1-2 is listed twice but still forms one cluster {1,2}; {3,4} forms another. Total: 2 clusters.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →