-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.rs
81 lines (77 loc) · 2.2 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
fn main() {
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0,0,0],
vec![0,1,0],
vec![0,0,0]
]), 2);
}
struct Solution {}
impl Solution {
pub fn unique_paths_with_obstacles(obstacle_grid: Vec<Vec<i32>>) -> i32 {
let (m, n) = (obstacle_grid.len() + 1, obstacle_grid[0].len() + 1);
if m == 2 || n == 2 { return if obstacle_grid.iter().any(|x| x.contains(&1)) { 0 } else { 1 } }
let mut grid = vec![vec![0; n]; m];
grid[0][1] = 1;
for i in 1..m {
for j in 1..n {
if obstacle_grid[i-1][j-1] == 0 {
grid[i][j] = grid[i-1][j] + grid[i][j-1];
}
}
}
grid[m-1][n-1]
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0,0,0],
vec![0,1,0],
vec![0,0,0]
]), 2);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0,0,0],
vec![0,1,1],
vec![0,0,0]
]), 1);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0,0,0],
vec![0,1,1],
vec![0,1,0]
]), 0);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0,0,0],
vec![1,1,1],
vec![0,1,0]
]), 0);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0,0,0],
vec![0,0,0],
vec![0,0,1]
]), 0);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0,1,0],
vec![1,0,0],
vec![0,0,0]
]), 0);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0,0,0],
vec![1,1,0],
vec![0,0,0]
]), 1);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![1],
]), 0);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![0],
]), 1);
assert_eq!(Solution::unique_paths_with_obstacles(vec![
vec![1,0,0],
vec![1,1,0],
vec![0,0,0]
]), 0);
}
}