Adjacency List Traversal
View as PDFYou are given an undirected graph with vertices numbered from to
. Starting at vertex
, run a breadth-first search.
When a vertex has multiple unvisited neighbors available, smaller-numbered vertices must be visited first. To do this, sort each adjacency list before running the search.
Input
The first line contains three integers ,
, and
, the number of vertices, the number of
edges, and the starting vertex.
The next lines each contain two integers
and
, meaning there is an undirected edge
between vertices
and
.
Output
Output one line containing the vertices in the order they are first visited by the BFS, separated by spaces.
Constraints
Example 1
Input
5 5 1
1 2
1 3
2 4
3 4
4 5
Output
1 2 3 4 5
Explanation
The BFS starts at . Vertices
and
are reached first, and vertex
is visited before
vertex
because it has the smaller number.
Example 2
Input
6 5 4
4 2
4 6
2 1
2 3
6 5
Output
4 2 6 1 3 5
Explanation
From vertex , the sorted neighbors are
and
. Vertex
is processed first, but vertex
was already discovered before vertices
and
.
Comments