#815
Hard Algorithms Bus routes
Array Hash Table Breadth-First Search
47.1% acceptance
Feb 22, 2026
4667
136
You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.
For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.
You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.
Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.
Solution
Rust
Time O(n³)
Space O(n)
/*
* You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.
* For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.
* You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.
* Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.
* Example 1:
* Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6
* Output: 2
* Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
* Example 2:
* Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
* Output: -1
* Constraints:
* 1 <= routes.length <= 500.
* 1 <= routes[i].length <= 105
* All the values of routes[i] are unique.
* sum(routes[i].length) <= 105
* 0 <= routes[i][j] < 106
* 0 <= source, target < 106
*/
impl Solution {
pub fn num_buses_to_destination(routes: Vec<Vec<i32>>, source: i32, target: i32) -> i32 {
if source == target { return 0; }
use std::collections::{HashMap, HashSet, VecDeque};
let mut stop_to_routes: HashMap<i32, Vec<usize>> = HashMap::new();
for (i, route) in routes.iter().enumerate() {
for &stop in route { stop_to_routes.entry(stop).or_default().push(i); }
}
let mut visited_stops: HashSet<i32> = HashSet::new();
let mut visited_routes: HashSet<usize> = HashSet::new();
let mut queue: VecDeque<i32> = VecDeque::new();
queue.push_back(source);
visited_stops.insert(source);
let mut buses = 0;
while !queue.is_empty() {
buses += 1;
let sz = queue.len();
for _ in 0..sz {
let stop = queue.pop_front().unwrap();
for &ri in stop_to_routes.get(&stop).unwrap_or(&vec![]) {
if visited_routes.contains(&ri) { continue; }
visited_routes.insert(ri);
for &ns in &routes[ri] {
if ns == target { return buses; }
if !visited_stops.contains(&ns) {
visited_stops.insert(ns);
queue.push_back(ns);
}
}
}
}
}
-1
}
}