https://leetcode.com/problems/out-of-boundary-paths/
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.
Example 1: Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 Output: 6 Example 2: Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 Output: 12
Constraints:
1 <= m, n <= 50
0 <= maxMove <= 50
0 <= startRow < m
0 <= startColumn < n
- code BFS TLE, can’t store the state
class Solution {
int[][] directions = {{1,0}, {-1,0}, {0,1}, {0,-1}};
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
Queue<int[]> q = new ArrayDeque<>();
q.offer(new int[]{startRow, startColumn, maxMove});
int outPaths = 0;
while(!q.isEmpty()){
// q.stream().map(a -> Arrays.toString(a)).forEach(System.out::println);
int[] curXYM = q.poll();
if (curXYM[2] == 0) continue;
for (int[] d: directions){
int nx = curXYM[0] + d[0];
int ny = curXYM[1] + d[1];
if (nx < 0 || nx == m || ny < 0 || ny == n){
outPaths++;
}else{
q.offer(new int[]{nx, ny, curXYM[2] - 1});
}
}
}
return outPaths % (int)(Math.pow(10, 9) + 7);
}
}
- code
class Solution {
int[][][] memo;
int M, N;
int MOD = (int) Math.pow(10, 9) + 7;
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
memo = new int[m][n][maxMove + 1];
M = m;
N = n;
for (int[][] t: memo) for (int[] tt: t) Arrays.fill(tt, -1);
return dfs(startRow, startColumn, maxMove, memo);
}
public int dfs(int i, int j, int maxMove, int[][][] memo){
if (i < 0 || j < 0 || i == M || j == N) return 1;
if (maxMove == 0) return 0;
if (memo[i][j][maxMove] >= 0) return memo[i][j][maxMove];
memo[i][j][maxMove] = ((dfs(i-1, j, maxMove - 1, memo) % MOD
+ dfs(i+1, j, maxMove - 1, memo) % MOD) % MOD
+ (dfs(i, j-1, maxMove - 1, memo) % MOD
+ dfs(i, j+1, maxMove - 1, memo) % MOD) % MOD) % MOD;
return memo[i][j][maxMove];
}
}