Challenge: Fewest Roads
Completed
Read a graph, then a start and a goal. Print the smallest number of roads needed to get from start to goal using BFS, or -1 if it can't be reached.
Input
Line 1: n m – the number of places (numbered 0 to n − 1) and the number of roads. Then m lines a b: a two-way road between a and b.
Last line: start goal.
Output
One number.
Example
Input
6 6 0 1 0 2 1 3 2 4 3 5 4 5 0 5
Output
3
Editor
Python
Hints
dist starts as -1 everywhere except dist[start] = 0.
When you first reach w from v, dist[w] = dist[v] + 1.
Solution explanation
BFS reaches every place first along a path with the fewest roads.
Show solution
from collections import deque
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
g[a].append(b)
g[b].append(a)
s, t = map(int, input().split())
dist = [-1] * n
dist[s] = 0
q = deque([s])
while q:
v = q.popleft()
for w in g[v]:
if dist[w] == -1:
dist[w] = dist[v] + 1
q.append(w)
print(dist[t]) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module