Description:
There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 109 + 7.
Example 1:
Example 2:
Note:
- Once you move the ball out of boundary, you cannot move it back.
- The length and height of the grid is in range [1,50].
- N is in range [0,50].
问题描述
在m * n 的棋盘上有一个初始位置为(i, j)的球,你可以将它向四个方向(上,下,左,右)移动,并且可以把它移出棋盘。然而你最多只能将球移动N次。返回将球移出棋盘的路径个数。数目可能会很大,先对 109+7 10 9 + 7 取余
问题分析
这道题与下面这道题类似
https://leetcode.com/problems/knight-probability-in-chessboard/description/
用DFS + Memorization做就可以了
解法1(dfs + memorization):
class Solution {
private int M = 1000000007;
private int[][][] memo;
public int findPaths(int m, int n, int N, int i, int j) {
memo = new int[m][n][N + 1];
for(int[][] temp1 : memo){
for(int[] temp2 : temp1) Arrays.fill(temp2,-1);
}
return find(m,n,N,i,j);
}
public int find(int m,int n,int N,int i,int j){
if(i < 0 || j < 0 || i == m || j == n) return 1;
if(N == 0) return 0;
if(memo[i][j][N] >= 0) return memo[i][j][N];
memo[i][j][N] = ((find(m,n,N - 1,i - 1,j) + find(m,n,N - 1,i,j - 1)) % M + (find(m,n,N - 1,i + 1,j) + find(m,n,N - 1,i,j + 1)) % M) % M;
return memo[i][j][N];
}
}
解法2(动态规划):
public class Solution {
public int findPaths(int m, int n, int N, int x, int y) {
int M = 1000000000 + 7;
int dp[][] = new int[m][n];
dp[x][y] = 1;
int count = 0;
for (int moves = 1; moves <= N; moves++) {
int[][] temp = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == m - 1)
count = (count + dp[i][j]) % M;
if (j == n - 1)
count = (count + dp[i][j]) % M;
if (i == 0)
count = (count + dp[i][j]) % M;
if (j == 0)
count = (count + dp[i][j]) % M;
temp[i][j] = (((i > 0 ? dp[i - 1][j] : 0) + (i < m - 1 ? dp[i + 1][j] : 0)) % M + ((j > 0 ? dp[i][j - 1] : 0) + (j < n - 1 ? dp[i][j + 1] : 0)) % M) % M;
}
}
dp = temp;
}
return count;
}
}