diff --git a/src/problem/mod.rs b/src/problem/mod.rs index e771d8c..98d971e 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -84,4 +84,5 @@ mod p2671_frequency_tracker; mod p2617_minimum_number_of_visited_cells_in_a_grid; mod p2549_count_distinct_numbers_on_board; mod p322_coin_change; -mod p518_coin_change_ii; \ No newline at end of file +mod p518_coin_change_ii; +mod p2642_design_graph_with_shortest_path_calculator; \ No newline at end of file diff --git a/src/problem/p2642_design_graph_with_shortest_path_calculator.rs b/src/problem/p2642_design_graph_with_shortest_path_calculator.rs new file mode 100644 index 0000000..93cf764 --- /dev/null +++ b/src/problem/p2642_design_graph_with_shortest_path_calculator.rs @@ -0,0 +1,82 @@ +/** + * [2642] Design Graph With Shortest Path Calculator + */ +pub struct Solution {} + +// submission codes start here +use std::{cmp::Reverse, collections::BinaryHeap}; + +struct Graph { + graph: Vec>, +} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Graph { + fn new(n: i32, edges: Vec>) -> Self { + let n = n as usize; + + let mut graph = vec![vec![]; n]; + + for edge in &edges { + let x = edge[0] as usize; + let y = edge[1] as usize; + + graph[x].push((y, edge[2])); + } + + Graph { graph } + } + + fn add_edge(&mut self, edge: Vec) { + let x = edge[0] as usize; + let y = edge[1] as usize; + + self.graph[x].push((y, edge[2])); + } + + fn shortest_path(&self, node1: i32, node2: i32) -> i32 { + let (start, end) = (node1 as usize, node2 as usize); + let mut queue = BinaryHeap::new(); + let mut distances = vec![i32::MAX; self.graph.len()]; + distances[start] = 0; + queue.push((Reverse(0), start)); + + while !queue.is_empty() { + let (cost, now) = queue.pop().unwrap(); + + if now == end { + return cost.0; + } + + for &(next, dis) in &self.graph[now] { + if distances[next] > cost.0 + dis { + distances[next] = cost.0 + dis; + queue.push((Reverse(distances[next]), next)); + } + } + + } + + -1 + } +} + +/** + * Your Graph object will be instantiated and called as such: + * let obj = Graph::new(n, edges); + * obj.add_edge(edge); + * let ret_2: i32 = obj.shortest_path(node1, node2); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2642() {} +}