Skip to content

Commit

Permalink
Added graph with shortest path solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 16, 2024
1 parent b320e6d commit f93d51d
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ programming challenges completed in other languages.

- [Kth Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance)
- [Escape a Large Maze](https://leetcode.com/problems/escape-a-large-maze)
- [Graph With Stortest Path](https://leetcode.com/problems/design-graph-with-shortest-path-calculator/)

### Other

Expand Down
42 changes: 42 additions & 0 deletions src/leetcode/graph_shortest_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use std::{cmp::Reverse, collections::BinaryHeap};

struct Graph {
nodes: Vec<Vec<(usize, i32)>>,
}

impl Graph {
fn new(n: i32, edges: Vec<Vec<i32>>) -> Self {
let mut nodes = vec![vec![]; n as usize];
for edge in edges {
nodes[edge[0] as usize].push((edge[1] as usize, edge[2]));
}
Self { nodes }
}

fn add_edge(&mut self, edge: Vec<i32>) {
self.nodes[edge[0] as usize].push((edge[1] as usize, edge[2]));
}

fn shortest_path(&self, src: i32, dest: i32) -> i32 {
let (src, dest) = (src as usize, dest as usize);
let mut to_visit = BinaryHeap::from([Reverse((0, src))]);
let mut distances = vec![i32::MAX; self.nodes.len()];
distances[src] = 0;

while let Some(Reverse((cost, current_node))) = to_visit.pop() {
if current_node == dest {
return cost;
}

for (neighbor, dist) in &self.nodes[current_node] {
let new_cost = dist + cost;
if new_cost < distances[*neighbor] {
distances[*neighbor] = new_cost;
to_visit.push(Reverse((new_cost, *neighbor)));
}
}
}

-1
}
}
5 changes: 3 additions & 2 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ mod find_integer;
mod find_pairs;
mod freq_sort;
mod gas_station;
mod graph_shortest_path;
mod grid_illumination;
mod hamming_distance;
mod hour_glass_sum;
Expand Down Expand Up @@ -64,6 +65,7 @@ mod max_subarray_sum;
mod max_substr_between_duplicates;
mod maximum_product;
mod maximum_xor;
mod merge_intervals;
mod merge_lists;
mod min_array_end;
mod min_bit_flips;
Expand Down Expand Up @@ -132,5 +134,4 @@ mod unique_occurrences;
mod valid_parenthesis;
mod x_kind;
mod xor_subarray;
mod zero_or_one;
mod merge_intervals;
mod zero_or_one;

0 comments on commit f93d51d

Please sign in to comment.