LeetCode 980. Unique Paths III

Problem Statement


impl Solution {
fn dfs(grid: &mut Vec<Vec<i32>>, x: i32, y: i32, n: i32) -> i32 {
if x < 0 || x == grid[0].len() as i32 || y < 0 || y == grid.len() as i32 ||
grid[y as usize][x as usize] == -1 {
return 0;
}
let (yy, xx) = (y as usize, x as usize);
if grid[yy][xx] == 2 {
if n == 0 {
return 1;
} else {
return 0;
}
}
grid[yy][xx] = -1;
let ans = Self::dfs(grid, x + 1, y, n - 1) +
Self::dfs(grid, x - 1, y, n - 1) +
Self::dfs(grid, x, y + 1, n - 1) +
Self::dfs(grid, x, y - 1, n - 1);
grid[yy][xx] = 0;
return ans;
}
pub fn unique_paths_iii(grid: Vec<Vec<i32>>) -> i32 {
let (mut sx, mut sy, mut n) = (0, 0, 1);
let mut g = grid.clone();
for i in 0..g.len() {
for j in 0..g[0].len() {
if g[i][j] == 0 {
n += 1;
} else if grid[i][j] == 1 {
sx = j; sy = i;
}
}
}

return Self::dfs(&mut g, sx as i32, sy as i32, n);
}
}