576. Out of Boundary Paths

576. Out of Boundary Paths

Question

There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.

Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.

Solution

DFS,记忆化搜索哦剪枝。

记忆化搜索

三维数组memo[][][]用来记录起点为startRow, startColumn,剩余距离为maxMove时的总路径数。
注意需要将memo[][][]所有数值初始化为-1。否则在进行BFS搜索时,无法对maxMove等于0的情况进行剪枝。

DFS

当当前位置越界,则为一个有效路径,返回1。
当剩余步数为0时,无法继续移动,返回0。

如果当前位置与剩余步数的状态已经被搜索并记录过,则直接返回memo[startRow][startColumn][maxMove]。
如果未搜索,则将maxMove减一,并向四周移动一格,对当前位置的四个方向进行递归。
记忆当前位置的四个方向的总路径数之和,模除后返回。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
final int MOD = (int) Math.pow(10, 9) + 7;
long[][][] memo;
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
memo = new long[m][n][maxMove];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
for(int k = 0; k < maxMove; k++){
memo[i][j][k] = -1;
}
}
}
return (int) dfs(m, n, maxMove, startRow, startColumn);
}

private long dfs(int m, int n, int maxMove, int startRow, int startColumn){
if(startRow < 0 || startRow >= m || startColumn < 0 || startColumn >= n) return 1;
if(maxMove == 0) return 0;

maxMove--;
if(memo[startRow][startColumn][maxMove] != -1) return memo[startRow][startColumn][maxMove];

long left = dfs(m, n, maxMove, startRow-1, startColumn);
long right = dfs(m, n, maxMove, startRow+1, startColumn);
long up = dfs(m, n, maxMove, startRow, startColumn+1);
long down = dfs(m, n, maxMove, startRow, startColumn-1);

memo[startRow][startColumn][maxMove] = (left + right + up + down) % MOD;
return memo[startRow][startColumn][maxMove];
}
}
Author

Xander

Posted on

2022-07-16

Updated on

2022-07-16

Licensed under

Comments