BFS Shortest Distances
View as PDF
Submit solution
Points:
100
Time limit:
1.0s
PyPy 3
3.0s
Python 3
3.0s
Memory limit:
500M
Problem type
You are given an undirected graph with vertices numbered from
to
, and a starting
vertex
.
Find the minimum number of edges needed to reach every vertex from . If a vertex cannot be
reached, its distance is
-1.
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
Print integers: the distances from
to vertices
, in order. Print
-1
for each unreachable vertex.
Constraints
Example 1
Input
5 4 1
1 2
1 3
2 4
4 5
Output
0 1 1 2 3
Example 2
Input
6 2 4
2 4
5 6
Output
-1 1 -1 0 -1 -1
Explanation
Only vertex is reachable from vertex
in this graph.
Comments