20240917 finished.

This commit is contained in:
jackfiled 2024-09-17 15:21:16 +08:00
parent 81a6d4f160
commit 7716ee0d00
2 changed files with 92 additions and 1 deletions

View File

@ -238,3 +238,4 @@ mod p2398_maximum_number_of_robots_within_budget;
mod p2390_removing_stars_from_a_string; mod p2390_removing_stars_from_a_string;
mod p2848_points_that_intersect_with_cars; mod p2848_points_that_intersect_with_cars;
mod p1184_distance_between_bus_stops; mod p1184_distance_between_bus_stops;
mod p815_bus_routes;

View File

@ -0,0 +1,90 @@
/**
* [815] Bus Routes
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn num_buses_to_destination(routes: Vec<Vec<i32>>, source: i32, target: i32) -> i32 {
use std::collections::{VecDeque, HashMap};
if source == target {
return 0;
}
let n = routes.len();
// 存储经过某一站的公交线路
let mut map: HashMap<i32, Vec<usize>> = 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));
}
}