diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 3263b1b..2b6d510 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -237,4 +237,5 @@ mod p2576_find_the_maximum_number_of_marked_indices; mod p2398_maximum_number_of_robots_within_budget; mod p2390_removing_stars_from_a_string; mod p2848_points_that_intersect_with_cars; -mod p1184_distance_between_bus_stops; \ No newline at end of file +mod p1184_distance_between_bus_stops; +mod p815_bus_routes; \ No newline at end of file diff --git a/src/problem/p815_bus_routes.rs b/src/problem/p815_bus_routes.rs new file mode 100644 index 0000000..2638690 --- /dev/null +++ b/src/problem/p815_bus_routes.rs @@ -0,0 +1,90 @@ +/** + * [815] Bus Routes + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn num_buses_to_destination(routes: Vec>, source: i32, target: i32) -> i32 { + use std::collections::{VecDeque, HashMap}; + + if source == target { + return 0; + } + + let n = routes.len(); + // 存储经过某一站的公交线路 + let mut map: HashMap> = HashMap::new(); + // 存储不同公交线路之前的联通情况 + let mut edge = vec![vec![false; n]; n]; + + for (bus, stations) in routes.iter().enumerate() { + for &station in stations { + if let Some(connected_stations) = map.get(&station) { + for &connected_station in connected_stations { + edge[connected_station][bus] = true; + edge[bus][connected_station] = true; + } + } + + let entry = map.entry(station).or_insert(vec![]); + entry.push(bus); + } + } + + let mut distances = vec![-1; n]; + let mut queue = VecDeque::new(); + + if let Some(source_buses) = map.get(&source) { + for &bus in source_buses { + distances[bus] = 1; + queue.push_back(bus); + } + } else { + // 没有任何公交车经过起始站点 + return -1; + } + + while !queue.is_empty() { + let now = queue.pop_front().unwrap(); + + for next in 0..n { + if edge[now][next] && distances[next] == -1 { + distances[next] = distances[now] + 1; + queue.push_back(next); + } + } + } + + let mut result = i32::MAX; + + if let Some(target_buses) = map.get(&target) { + for &bus in target_buses { + result = result.min(distances[bus]); + } + } else { + // 没有任何公交车经过终点站点 + return -1; + } + + if result == i32::MAX { + -1 + } else { + result + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_815() { + assert_eq!(2, Solution::num_buses_to_destination(vec![vec![1, 2, 7], vec![3, 6, 7]], 1, 6)); + } +}