feat: simplify min_path_sum implementation by removing unused code and optimizing grid updates
This commit is contained in:
parent
c6a939c5e0
commit
2026979f5e
@ -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<Vec<i32>>) -> i32 {
|
||||
let directions: Vec<(usize, usize)> = vec![(1, 0), (0, 1)];
|
||||
pub fn min_path_sum(mut grid: Vec<Vec<i32>>) -> 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::<Reverse<Point>>::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]
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user