题目描述
在m×n的二进制矩阵中,1代表不可通过,0代表可通过。机器人从(0,0)出发,每次可向下或向右移动一格。问走到(m-1,n-1)一共有多少条路径?
代码
def get_path_num(matrix: List[List[int]]) -> int:
m,n=len(matrix),len(matrix[0])
total=0
moves=[(1,0),(0,1)]
def dfs(x,y):
if x==m-1 and y==n-1:
nonlocal total
total+=1
for move in moves:
x1,y1=x+move[0],y+move[1]
if 0<=x1<m and 0<=y1<n and matrix[x1][y1]==0:
matrix[x1][y1]=1
dfs(x1,y1)
matrix[x1][y1]=0
if matrix[0][0]==1:
return 0
else:
matrix[0][0]=1
dfs(0,0)
return total
DFS,就是回溯啦。