BFS Shortest Distances
You are given an undirected graph with n vertices numbered from 1 to n, and a starting vertex s.
Find the minimum number of edges needed to reach every vertex from s. If a vertex cannot be
reached, its distance is -1.
Input
The first line contains three integers n, m, and s: the number of vertices, the number of edges, and the starting vertex.
The next m lines each contain two integers a and b, meaning there is an undirected edge between vertices a and b.
Output
Print n integers: the distances from s to vertices 1,2,…,n, in order. Print -1
for each unreachable vertex.
Constraints
- 1≤n≤200000
- 0≤m≤300000
- 1≤s≤n
- 1≤a,b≤n
Example 1
5 4 1
1 2
1 3
2 4
4 5
0 1 1 2 3
Example 2
6 2 4
2 4
5 6
-1 1 -1 0 -1 -1
Explanation
Only vertex 2 is reachable from vertex 4 in this graph.
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.