feat: add initial implementation of minimum path sum solution
This commit is contained in:
parent
0aa11d31a2
commit
c6a939c5e0
7
64_minimum_path_sum/Cargo.lock
generated
Normal file
7
64_minimum_path_sum/Cargo.lock
generated
Normal file
@ -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"
|
6
64_minimum_path_sum/Cargo.toml
Normal file
6
64_minimum_path_sum/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "minimum_path_sum"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
71
64_minimum_path_sum/src/main.rs
Normal file
71
64_minimum_path_sum/src/main.rs
Normal file
@ -0,0 +1,71 @@
|
||||
use std::cmp::Reverse;
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
|
||||
struct Solution;
|
||||
|
||||
impl Solution {
|
||||
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> 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::<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,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user