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:
Input: m = 2, n = 2, N = 2, i = 0, j = 0
Output: 6
Explanation:
Example 2:
Input: m = 1, n = 3, N = 3, i = 0, j = 1
Output: 12
Explanation:
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].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/out-of-boundary-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int findPaths(int m, int n, int N, int i, int j) {
int [][][]dp=new int[N+1][m][n];//其中dp[k][i][j]表示总共走k步,从(i,j)位置走出边界的总路径数
for(int k=1;k<=N;k++) {
for(int x=0;x<m;x++) {
for(int y=0;y<n;y++) {
int left=x==0?1:dp[k-1][x-1][y];
int right=x==m-1?1:dp[k-1][x+1][y];
int up=y==0?1:dp[k-1][x][y-1];
int down=y==n-1?1:dp[k-1][x][y+1];
dp[k][x][y]=(int) (((long)left+right+up+down)%1000000007);//要转换成long类型
}
}
}
return dp[N][i][j];
}
}
贴一个我的超时的方法
class Solution {
private int count;
public int findPaths(int m, int n, int N, int i, int j) {
dfs(m,n,N-1,i-1,j);//往上
dfs(m,n,N-1,i+1,j);//往下
dfs(m,n,N-1,i,j-1);//往左
dfs(m,n,N-1,i,j+1);//往右
return (int) (count%(Math.pow(10, 9)+7));
}
private void dfs(int m, int n, int N, int row, int cos) {
// TODO Auto-generated method stub
if(N>=0&&(row<0||row+1>m||cos<0||cos+1>n)) {
count=(int) ((count+1)%(Math.pow(10, 9)+7));
return ;
}
if(N<0) {
return ;
}
dfs(m,n,N-1,row-1,cos);//往上
dfs(m,n,N-1,row+1,cos);//往下
dfs(m,n,N-1,row,cos-1);//往左
dfs(m,n,N-1,row,cos+1);//往右
}
}