From 2026979f5e5737deca0ab3bf839cf5b2d131b1dc Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Mon, 18 Aug 2025 16:06:42 +0800 Subject: [PATCH] feat: simplify min_path_sum implementation by removing unused code and optimizing grid updates --- 64_minimum_path_sum/src/main.rs | 65 ++++++--------------------------- 1 file changed, 11 insertions(+), 54 deletions(-) diff --git a/64_minimum_path_sum/src/main.rs b/64_minimum_path_sum/src/main.rs index 0f693d4..56deb42 100644 --- a/64_minimum_path_sum/src/main.rs +++ b/64_minimum_path_sum/src/main.rs @@ -1,5 +1,3 @@ -use std::cmp::Reverse; - fn main() { println!("Hello, world!"); } @@ -7,65 +5,24 @@ fn main() { struct Solution; impl Solution { - pub fn min_path_sum(grid: Vec>) -> i32 { - let directions: Vec<(usize, usize)> = vec![(1, 0), (0, 1)]; + pub fn min_path_sum(mut grid: Vec>) -> i32 { let rows = grid.len(); let cols = grid[0].len(); - let mut visited = vec![vec![false; cols]; rows]; + for i in 1..rows { + grid[i][0] += grid[i - 1][0]; + } - let mut distances = vec![vec![i32::MAX; cols]; rows]; - distances[0][0] = grid[0][0]; + for j in 1..cols { + grid[0][j] += grid[0][j - 1]; + } - 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, - })); - } + for i in 1..rows { + for j in 1..cols { + grid[i][j] = std::cmp::min(grid[i][j] + grid[i - 1][j], grid[i][j] + grid[i][j - 1]) } } - 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)) + grid[rows - 1][cols - 1] } }