这个题解使用了记忆化递归的方法。首先判断如果最大移动次数为0,直接返回0。然后定义了一个递归函数countPaths,用来计算从当前位置(currX, currY)出发,在剩余的maxMove步内出界的路径数量。如果只剩下1步,那么只需判断当前位置是否在边界上,在的话就返回1,否则返回0。如果还有多步,就分别向上下左右四个方向递归调用countPaths,如果某个方向已经出界,则该方向的返回值为1。最后将四个方向的结果求和取模即可。主函数中调用countPaths(startRow, startColumn, maxMove)得到最终结果。
时间复杂度: O(m * n * maxMove)
空间复杂度: O(m * n * maxMove)
class Solution:
def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
MOD = 10 ** 9 + 7
if maxMove == 0:
return 0
@cache
def countPaths(currX: int, currY: int, maxMove: int) -> int:
# 如果只剩下1步,判断当前位置是否在边界上
if maxMove == 1:
return (currX == 0) + (currX == m - 1) + (currY == 0) + (currY == n - 1)
# 否则向四个方向递归调用,并将结果求和
return sum([
countPaths(currX - 1, currY, maxMove - 1) if currX > 0 else 1, # 向上移动
countPaths(currX + 1, currY, maxMove - 1) if currX < m - 1 else 1, # 向下移动
countPaths(currX, currY - 1, maxMove - 1) if currY > 0 else 1, # 向左移动
countPaths(currX, currY + 1, maxMove - 1) if currY < n - 1 else 1 # 向右移动
]) % MOD
return countPaths(startRow, startColumn, maxMove)