Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e06a49e

Browse files
author
guangsheng.li01
committed
Solved 0931
1 parent 49fd41c commit e06a49e

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/a0931_minimum_falling_path_sum.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* [0931] minimum-falling-path-sum
3+
*/
4+
5+
pub struct Solution {}
6+
7+
// solution impl starts here
8+
9+
use std::cmp::min;
10+
impl Solution {
11+
pub fn min_falling_path_sum(a: Vec<Vec<i32>>) -> i32 {
12+
let size = a.len();
13+
let mut dp = a;
14+
for row in 2..=size {
15+
let row = size - row;
16+
for col in 0..size {
17+
let next_row = row + 1;
18+
match col {
19+
col if col == 0 => {
20+
dp[row][col] += min(dp[next_row][col], dp[next_row][col + 1])
21+
}
22+
col if col == size - 1 => {
23+
dp[row][col] += min(dp[next_row][col], dp[next_row][col - 1])
24+
}
25+
col => {
26+
dp[row][col] += Solution::min3(
27+
dp[next_row][col - 1],
28+
dp[next_row][col],
29+
dp[next_row][col + 1],
30+
)
31+
}
32+
}
33+
}
34+
}
35+
36+
let mut res = std::i32::MAX;
37+
for i in &dp[0] {
38+
res = min(res, *i);
39+
}
40+
res
41+
}
42+
43+
#[inline]
44+
pub fn min3<T: Ord>(v1: T, v2: T, v3: T) -> T {
45+
v3.min(v1.min(v2))
46+
}
47+
}
48+
49+
// solution impl ends here
50+
51+
// solution tests starts here
52+
53+
#[cfg(test)]
54+
mod tests {
55+
use super::*;
56+
57+
#[test]
58+
fn test_case0() {
59+
assert_eq!(
60+
Solution::min_falling_path_sum(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]),
61+
12
62+
);
63+
}
64+
}
65+
66+
// solution tests ends here

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ mod a0404_sum_of_left_leaves;
1313
mod a0617_merge_two_binary_trees;
1414
mod a0643_maximum_average_subarray_i;
1515
mod a0929_unique_email_addresses;
16+
mod a0931_minimum_falling_path_sum;
1617
mod a0937_reorder_data_in_log_files;
1718
mod a1047_remove_all_adjacent_duplicates_in_string;
1819
mod a1200_minimum_absolute_difference;

0 commit comments

Comments
 (0)