Problem :

https://leetcode.com/problems/unique-paths-iii/


My Solution :

class Solution:
def uniquePathsIII(self, grid):
def dfs(r, c, remain):
if grid[r][c] == 2:
if remain == 0:
self.ans += 1
return
grid[r][c] = -1
for y, x in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if (0 <= y < len(grid) and
0 <= x < len(grid[0]) and
grid[y][x] in (0, 2)):
dfs(y, x, remain-1)
grid[r][c] = 0

self.ans = 0
remain = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] in (0, 1):
remain += 1
if grid[r][c] == 1:
R, C = r, c
dfs(R, C, remain)
return self.ans