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 adjacentcell 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].
DFS + memorization,程序如下所示:
class Solution {
private final int MOD = 1000000007;
private Map<String, Integer> map = new HashMap<>();
public int findPaths(int m, int n, int N, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n){
return 1;
}
if (N == 0){
return 0;
}
String key = i + "," + j + ", " + N;
if (map.containsKey(key)){
return map.get(key);
}
int sum = 0;
sum += findPaths(m, n, N - 1, i + 1, j);
sum %= MOD;
sum += findPaths(m, n, N - 1, i - 1, j);
sum %= MOD;
sum += findPaths(m, n, N - 1, i, j + 1);
sum %= MOD;
sum += findPaths(m, n, N - 1, i, j - 1);
sum = sum%MOD;
map.put(key, sum);
return sum;
}
}