From c6a939c5e0c19bd50b2540f855df6552165eeb17 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Mon, 18 Aug 2025 15:55:06 +0800 Subject: [PATCH] feat: add initial implementation of minimum path sum solution --- 64_minimum_path_sum/Cargo.lock | 7 ++++ 64_minimum_path_sum/Cargo.toml | 6 +++ 64_minimum_path_sum/src/main.rs | 71 +++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 64_minimum_path_sum/Cargo.lock create mode 100644 64_minimum_path_sum/Cargo.toml create mode 100644 64_minimum_path_sum/src/main.rs diff --git a/64_minimum_path_sum/Cargo.lock b/64_minimum_path_sum/Cargo.lock new file mode 100644 index 0000000..3b6f9de --- /dev/null +++ b/64_minimum_path_sum/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "minimum_path_sum" +version = "0.1.0" diff --git a/64_minimum_path_sum/Cargo.toml b/64_minimum_path_sum/Cargo.toml new file mode 100644 index 0000000..d8eac2b --- /dev/null +++ b/64_minimum_path_sum/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "minimum_path_sum" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/64_minimum_path_sum/src/main.rs b/64_minimum_path_sum/src/main.rs new file mode 100644 index 0000000..0f693d4 --- /dev/null +++ b/64_minimum_path_sum/src/main.rs @@ -0,0 +1,71 @@ +use std::cmp::Reverse; + +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn min_path_sum(grid: Vec>) -> i32 { + let directions: Vec<(usize, usize)> = vec![(1, 0), (0, 1)]; + let rows = grid.len(); + let cols = grid[0].len(); + + let mut visited = vec![vec![false; cols]; rows]; + + let mut distances = vec![vec![i32::MAX; cols]; rows]; + distances[0][0] = grid[0][0]; + + let mut priority_queue = std::collections::BinaryHeap::>::new(); + priority_queue.push(Reverse(Point { + distance: distances[0][0], + loc: (0, 0), + })); + + while !priority_queue.is_empty() { + let current = priority_queue.pop().unwrap().0; + + visited[current.loc.0][current.loc.1] = true; + + if current.loc == (rows - 1, cols - 1) { + return current.distance; + } + + for &direction in &directions { + let new_loc = (current.loc.0 + direction.0, current.loc.1 + direction.1); + if new_loc.0 >= rows || new_loc.1 >= cols { + continue; + } + if visited[new_loc.0][new_loc.1] { + continue; + } + + let new_distance = current.distance + grid[new_loc.0][new_loc.1]; + if new_distance < distances[new_loc.0][new_loc.1] { + distances[new_loc.0][new_loc.1] = new_distance; + priority_queue.push(Reverse(Point { + distance: new_distance, + loc: new_loc, + })); + } + } + } + + 0 + } +} + +#[derive(PartialEq, Eq, PartialOrd)] +struct Point { + distance: i32, + loc: (usize, usize), +} + +impl Ord for Point { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.distance + .cmp(&other.distance) + .then(self.loc.cmp(&other.loc)) + } +}