Challenge: Fewest Train Changes
Completed
Stations are linked by train lines. Print the fewest number of rides needed to get from station s to station t, or -1 if it's impossible. Use BFS.
Input
Line 1: n m – people/places are numbered 1 to n, and there are m links. Then m lines u v: a two-way link between u and v.
Last line: s t.
Output
The fewest rides, or -1.
Example
Input
6 6 1 2 1 3 2 4 3 4 4 5 5 6 1 6
Output
4
Editor
Java
Hints
dist[] starts at -1 for every station; dist[s] = 0.
BFS: when you first reach a station, its distance is dist[cur] + 1.
Solution explanation
BFS finds the fewest edges in O(n + m). Stations never reached keep −1.
Show solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i <= n; i++) g.add(new ArrayList<Integer>());
for (int i = 0; i < m; i++) {
int u = sc.nextInt(), v = sc.nextInt();
g.get(u).add(v);
g.get(v).add(u);
}
int s = sc.nextInt(), t = sc.nextInt();
int[] dist = new int[n + 1];
Arrays.fill(dist, -1);
ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
dist[s] = 0;
queue.offer(s);
while (!queue.isEmpty()) {
int cur = queue.poll();
for (int next : g.get(cur)) {
if (dist[next] == -1) {
dist[next] = dist[cur] + 1;
queue.offer(next);
}
}
}
System.out.println(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