Number of connected components
InterviewTime limit3sMemory limit512 MB
Count the connected components of an undirected graph given its vertices and edges.
Problem
You are given an undirected graph. Write a program that counts its connected components.
A connected component is a maximal set of vertices that are linked to each other by paths. Any two vertices in the same component have a path between them, and no path joins two vertices in different components. A vertex with no incident edge forms a component by itself.
Input
The first line contains the number of vertices and the number of edges , separated by a space. (, )
Each of the next lines contains the two endpoints and of an edge. (, ) The same edge is given only once.
Output
Print the number of connected components on the first line.