576. The number of paths out of bounds
For a given mesh and a ball of m × n. The initial coordinates of the ball is (i, j), can you move to the ball adjacent cells, or upward, moving the ball through the mesh boundary on the lower, left, and right directions. However, you can move up to N times. Find out the number of paths can be moved out of the boundary of the ball. The answer may be very large, the return value is the result 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:
Description:
Once the ball out of bounds, it can not be moved back into the grid.
The range of the length and height of the grid [1,50] of.
N in the range [0,50] of.
PS:
The traditional small series of DFS
chiefs made dynamic programming
class Solution {
private Integer[][][] cache;
public int findPaths(int m, int n, int N, int i, int j) {
cache = new Integer[m][n][N+1];
return dfs(m,n,N,j,i);
}
private int dfs(int rows,int cols,int times,int x,int y) {
if (isOutOfBoundary(x,y,rows,cols)) {
return 1;
}
if (0 == times) {
return 0;
}
if (null != cache[y][x][times]) {
return cache[y][x][times];
}
int res = (((dfs(rows,cols,times-1,x+1,y) + dfs(rows,cols,times-1,x-1,y)) % 1000000007) + ((dfs(rows,cols,times-1,x,y+1) + dfs(rows,cols,times-1,x,y-1)) % 1000000007)) % 1000000007;
cache[y][x][times] = res;
return res;
}
private boolean isOutOfBoundary(int x,int y,int rows,int cols) {
return x < 0 || x >= cols || y < 0 || y >= rows;
}
}
class Solution {
public int findPaths(int m, int n, int N, int i, int j) {
if(N <= 0) return 0;
int mod = 1000000007;
int ret = 0;
int[][] dp = new int[m][n]; // 保存第k步的结果
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for(int k = 1; k <= N; ++k) {
int[][] temp = new int[m][n]; // 保存第k-1步的结果
for(int x = 0; x < m; ++x) {
for(int y = 0; y < n; ++y) {
for(int[] dir : dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if(nx < 0 || nx >= m || ny < 0 || ny >= n)
temp[x][y] += 1;
else
temp[x][y] = (dp[nx][ny] + temp[x][y]) % mod;
}
}
}
dp = temp;
}
return dp[i][j];
}
}