In a graph where every edge counts as one step, breadth-first search finds the fewest-edge path between two vertices. Your program finds the distance and one such path.
What to build
A program that prints the shortest distance and path from s to t.
Requirements
- Read n, m, s and t on the first line, then m edges u v of an undirected graph on the vertices 1 to n.
- Run BFS from s, taking neighbours in increasing order, and remember the vertex from which each vertex was first reached.
- If t cannot be reached print
unreachable. Otherwise printdistance:and the number of edges of a shortest path, thenpath:and the vertices of the path found by the search, from s to t.
Input
The first line has n, m, s and t. Each of the next m lines has an edge.
Output
Two lines, or one line unreachable.
Constraints
1 ≤ n ≤ 30; 0 ≤ m ≤ 60.
Example
Input:
5 5 1 5
1 2
1 3
2 4
3 5
4 5
Output:
distance: 2
path: 1 3 5
Why it works
BFS reaches each vertex first along a route with the fewest edges, so the distance recorded when a vertex is found is its shortest distance. The parent is the vertex that found it, and following parents back to the start rebuilds the path; the increasing order of neighbours decides between equally short paths.
Examples
5 5 1 5 1 2 1 3 2 4 3 5 4 5
distance: 2 path: 1 3 5
4 2 1 4 1 2 3 4
unreachable
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Run BFS from s and record parent[w] = v when w is first found; the distance of w is the distance of v plus 1.
Hint 2
Take the neighbours of each vertex in increasing order, so the path is unique.
Hint 3
Follow the parents from t back to s, then reverse the list. If t was never found, print unreachable.
Solution
Show one correct solution (try it yourself first)
from collections import deque
n, m, s, t = map(int, input().split())
adj = {v: [] for v in range(1, n + 1)}
for _ in range(m):
u, v = map(int, input().split())
adj[u].append(v)
adj[v].append(u)
parent = {s: None}
queue = deque([s])
while queue:
v = queue.popleft()
for w in sorted(adj[v]):
if w not in parent:
parent[w] = v
queue.append(w)
if t not in parent:
print("unreachable")
else:
path = []
v = t
while v is not None:
path.append(v)
v = parent[v]
path.reverse()
print("distance:", len(path) - 1)
print("path:", *path)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step