From a602f53852f646889224dbca6a403ac6a193001f Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 10 Aug 2024 11:42:34 +0800 Subject: [PATCH] 20240810 Finished --- src/problem/mod.rs | 3 +- src/problem/p63_unique_paths_ii.rs | 55 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 src/problem/p63_unique_paths_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index fbe5460..853f407 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -199,4 +199,5 @@ mod p198_house_robber; mod p139_word_break; mod p300_longest_increasing_subsequence; mod p120_triangle; -mod p64_minimum_path_sum; \ No newline at end of file +mod p64_minimum_path_sum; +mod p63_unique_paths_ii; \ No newline at end of file diff --git a/src/problem/p63_unique_paths_ii.rs b/src/problem/p63_unique_paths_ii.rs new file mode 100644 index 0000000..127b9ff --- /dev/null +++ b/src/problem/p63_unique_paths_ii.rs @@ -0,0 +1,55 @@ +/** + * [63] Unique Paths II + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn unique_paths_with_obstacles(obstacle_grid: Vec>) -> i32 { + let (m, n) = (obstacle_grid.len(), obstacle_grid[0].len()); + let mut dp = vec![vec![0; n]; m]; + dp[0][0] = if obstacle_grid[0][0] == 1 { + 0 + } else { + 1 + }; + + for i in 0..m { + for j in 0..n { + if obstacle_grid[i][j] == 1 { + continue; + } + + let mut value = 0; + if i != 0 { + value += dp[i - 1][j]; + } + + if j != 0 { + value += dp[i][j - 1]; + } + + if i != 0 || j != 0 { + dp[i][j] = value; + } + } + } + + dp[m - 1][n - 1] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_63() { + assert_eq!(2, Solution::unique_paths_with_obstacles(vec![vec![0, 0, 0], vec![0, 1, 0], vec![0, 0, 0]])); + assert_eq!(0, Solution::unique_paths_with_obstacles(vec![vec![1]])); + } +}