rs: add “931. Minimum Falling Path Sum”

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-19 07:11:41 +01:00
parent 81ed1392cc
commit c9f0e952a5
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,29 @@
impl Solution {
fn get(matrix: &[Vec<i32>], row: isize, col: isize) -> Option<i32> {
let rows = matrix.len() as isize;
if row < 0 || row >= rows {
return None;
}
let cols = matrix[row as usize].len() as isize;
if col < 0 || col >= cols {
return None;
}
Some(matrix[row as usize][col as usize])
}
pub fn min_falling_path_sum(mut matrix: Vec<Vec<i32>>) -> i32 {
for row in (0..matrix.len() - 1).rev() {
for col in 0..matrix[row].len() {
matrix[row][col] += vec![-1, 0, 1]
.into_iter()
.filter_map(|dcol| Self::get(&matrix, row as isize + 1, col as isize + dcol))
.min()
.unwrap()
}
}
*matrix.first().unwrap().iter().min().unwrap()
}
}