feat: simplify min_path_sum implementation by removing unused code and optimizing grid updates

This commit is contained in:
SquidSpirit 2025-08-18 16:06:42 +08:00
parent c6a939c5e0
commit 2026979f5e

View File

@ -1,5 +1,3 @@
use std::cmp::Reverse;
fn main() { fn main() {
println!("Hello, world!"); println!("Hello, world!");
} }
@ -7,65 +5,24 @@ fn main() {
struct Solution; struct Solution;
impl Solution { impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 { pub fn min_path_sum(mut grid: Vec<Vec<i32>>) -> i32 {
let directions: Vec<(usize, usize)> = vec![(1, 0), (0, 1)];
let rows = grid.len(); let rows = grid.len();
let cols = grid[0].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]; for j in 1..cols {
distances[0][0] = grid[0][0]; grid[0][j] += grid[0][j - 1];
}
let mut priority_queue = std::collections::BinaryHeap::<Reverse<Point>>::new(); for i in 1..rows {
priority_queue.push(Reverse(Point { for j in 1..cols {
distance: distances[0][0], grid[i][j] = std::cmp::min(grid[i][j] + grid[i - 1][j], grid[i][j] + grid[i][j - 1])
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 grid[rows - 1][cols - 1]
}
}
#[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))
} }
} }