Connected Components
View as PDFYou are given an undirected graph with vertices numbered from
to
.
Find all connected components of the graph. Components are numbered in the order they are first
discovered by scanning vertices from to
. When an unvisited vertex is found, it starts the
next component, and every vertex reachable from it receives that component number.
Input
The first line contains two integers and
, the number of vertices and edges.
The next lines each contain two integers
and
, meaning there is an undirected edge
between vertices
and
.
Output
Print one integer , the number of connected components.
Then print integers: the component label of each vertex from
to
.
Constraints
Example 1
Input
5 3
1 2
2 3
4 5
Output
2
1 1 1 2 2
Explanation
Vertices form the first component, and vertices
form the second component.
Example 2
Input
6 2
2 4
3 6
Output
4
1 2 3 2 4 3
Explanation
Vertex starts component
. Vertices
and
form component
. Vertices
and
form component
. Vertex
starts component
.
Comments