diff --git a/src/dp/minimum_falling_path_sum.rs b/src/dp/minimum_falling_path_sum.rs new file mode 100644 index 0000000..cba93f4 --- /dev/null +++ b/src/dp/minimum_falling_path_sum.rs @@ -0,0 +1,48 @@ +//! https://leetcode.cn/problems/minimum-falling-path-sum +fn min_falling_path_sum(matrix: Vec>) -> i32 { + let m = matrix.len(); + let n = matrix[0].len(); + + let mut min = i32::MAX; + for j in 0..n { + min = min.min(search(0, j, m, n, 0, &matrix)); + } + + min +} + +fn search(row: usize, col:usize, m: usize, n: usize, mut sum: i32, matrix: &Vec>) -> i32 { + if row == m { + return sum; + } + let cur_val = matrix[row][col]; + sum += cur_val; + let mut min = search(row+1,col, m, n, sum, matrix); + if col >= 1 { + min = min.min(search(row+1,col-1, m, n, sum, matrix)); + } + if col < n-1 { + min = min.min(search(row+1,col+1, m, n, sum, matrix)); + } + min +} + +#[test] +fn test() { + for (matrix, min_path_sum) in [ + ( + vec_vec![ + [-19,57],[-40,-5] + ], + -59 + ), + ( + vec_vec![ + [2,1,3],[6,5,4],[7,8,9] + ], + 13 + ) + ] { + assert_eq!(min_falling_path_sum(matrix), min_path_sum); + } +} diff --git a/src/dp/mod.rs b/src/dp/mod.rs index af11623..cf68392 100644 --- a/src/dp/mod.rs +++ b/src/dp/mod.rs @@ -34,3 +34,4 @@ mod stone_game; mod trapping_rain_water; mod triangle; mod unique_paths; +mod minimum_falling_path_sum;