Challenge: Fewest Roads
Completed
Read a graph, then start goal. Print the fewest roads from start to goal using BFS, or -1.
Input
Line 1: n m – places numbered 0 to n − 1 and m 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
C++
Hints
dist = -1 everywhere except the start.
dist[w] = dist[v] + 1 the first time you reach w.
Solution explanation
BFS reaches every place first along a path with the fewest roads.
Show solution
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> g(n);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
int s, t;
cin >> s >> t;
vector<int> dist(n, -1);
queue<int> q;
dist[s] = 0;
q.push(s);
while (!q.empty()) {
int v = q.front();
q.pop();
for (int w : g[v])
if (dist[w] == -1) { dist[w] = dist[v] + 1; q.push(w); }
}
cout << dist[t] << endl;
return 0;
} 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