目录
题目-机器人的路劲-递归+hashmap
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish”)。
现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
网格中的障碍物和空位置分别用 1 和 0 来表示。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/unique-paths-ii
思路
递归+hasnMap
代码
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
# 统计障碍物的位置
r_max, c_max = len(obstacleGrid)-1, len(obstacleGrid[0])-1
obstacle = set()
for i in range(len(obstacleGrid)):
for j in range(len(obstacleGrid[i])):
if obstacleGrid[i][j] == 1:
obstacle.add(str(i) + "_" + str(j))
if i == r_max and j == c_max:
return 0
countMap = {}
# 递归函数
def methodCount(i, j):
if (i > r_max) or (j > c_max):
return 0
if (i == r_max) and (j == c_max):
return 1
key = str(i) + "_" + str(j)
if key in obstacle:
return 0
if key not in countMap:
res = m