Approach
Breadth-first search
For Bus Routes, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 31 lines of Java from the credited upstream file 815.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int numBusesToDestination(int[][] routes, int source, int target) {3 if (source == target)4 return 0;5 6 Map<Integer, List<Integer>> graph = new HashMap<>(); 7 Set<Integer> usedBuses = new HashSet<>();8 9 for (int i = 0; i < routes.length; ++i)10 for (final int route : routes[i]) {11 graph.putIfAbsent(route, new ArrayList<>());12 graph.get(route).add(i);13 }14 15 Queue<Integer> q = new ArrayDeque<>(List.of(source));16 17 for (int step = 1; !q.isEmpty(); ++step)18 for (int sz = q.size(); sz > 0; --sz) {19 for (final int bus : graph.getOrDefault(q.poll(), new ArrayList<>()))20 if (usedBuses.add(bus))21 for (final int nextRoute : routes[bus]) {22 if (nextRoute == target)23 return step;24 q.offer(nextRoute);25 }26 }27 28 return -1;29 }30}31