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

Commit 8dd0925

Browse files
author
guangsheng.li01
committed
Solved 0980
1 parent f9f2f1a commit 8dd0925

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

src/a0980_unique_paths_iii.rs

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
* [0980] unique-paths-iii
3+
*/
4+
5+
pub struct Solution {}
6+
7+
// solution impl starts here
8+
9+
impl Solution {
10+
pub fn unique_paths_iii(grid: Vec<Vec<i32>>) -> i32 {
11+
let mut grid = grid;
12+
let (mut x, mut r, mut c) = (1, 0, 0);
13+
for ir in 0..grid.len() {
14+
let row = &grid[ir];
15+
for ic in 0..row.len() {
16+
if row[ic] == 0 {
17+
x += 1;
18+
} else if row[ic] == 1 {
19+
r = ir as i32;
20+
c = ic as i32;
21+
}
22+
}
23+
}
24+
25+
Solution::dfs(&mut grid, r, c, x)
26+
}
27+
28+
fn dfs(grid: &mut Vec<Vec<i32>>, r: i32, c: i32, x: i32) -> i32 {
29+
if r < 0
30+
|| c < 0
31+
|| r >= grid.len() as i32
32+
|| c >= grid[0].len() as i32
33+
|| grid[r as usize][c as usize] == -1
34+
{
35+
return 0;
36+
}
37+
38+
let (ur, uc) = (r as usize, c as usize);
39+
if grid[ur][uc] == 2 {
40+
return if x == 0 { 1 } else { 0 };
41+
}
42+
43+
grid[ur][uc] = -1;
44+
let res = Solution::dfs(grid, r + 1, c, x - 1)
45+
+ Solution::dfs(grid, r - 1, c, x - 1)
46+
+ Solution::dfs(grid, r, c + 1, x - 1)
47+
+ Solution::dfs(grid, r, c - 1, x - 1);
48+
grid[ur][uc] = 0;
49+
res
50+
}
51+
}
52+
53+
// solution impl ends here
54+
55+
// solution tests starts here
56+
57+
#[cfg(test)]
58+
mod tests {
59+
use super::*;
60+
61+
#[test]
62+
fn test_case0() {
63+
assert_eq!(
64+
Solution::unique_paths_iii(vec![vec![1, 0, 0, 0], vec![0, 0, 0, 0], vec![0, 0, 2, -1]]),
65+
2
66+
);
67+
}
68+
69+
#[test]
70+
fn test_case1() {
71+
assert_eq!(
72+
Solution::unique_paths_iii(vec![vec![1, 0, 0, 0], vec![0, 0, 0, 0], vec![0, 0, 0, 2]]),
73+
4
74+
);
75+
}
76+
77+
#[test]
78+
fn test_case2() {
79+
assert_eq!(Solution::unique_paths_iii(vec![vec![0, 1], vec![2, 0]]), 0);
80+
}
81+
}
82+
83+
// solution tests ends here

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ mod a0931_minimum_falling_path_sum;
3030
mod a0937_reorder_data_in_log_files;
3131
mod a0949_largest_time_for_given_digits;
3232
mod a0973_k_closest_points_to_origin;
33+
mod a0980_unique_paths_iii;
3334
mod a1021_remove_outermost_parentheses;
3435
mod a1047_remove_all_adjacent_duplicates_in_string;
3536
mod a1200_minimum_absolute_difference;

0 commit comments

Comments
 (0)