https://leetcode.com/problems/out-of-boundary-paths/#/description
一个球在m * n的格子内,问多少种路径可以将它移出格子,最后的结果取模100000007
DP,时间复杂度O(m * n * step),dp[i][j]表示位置(i, j)的当前路径种数,内层循环每次初始化一个新的二维数组,用来记录当次遍历结果,遍历完之后赋值给cnt
public class Solution {
public int findPaths(int m, int n, int N, int a, int b) {
if (N <= 0) {
return 0;
}
int[][] cnt = new int[m][n];
int res = 0;
int mod = 1000000007;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
cnt[a][b] = 1;
for (int i = 0; i < N; i++) {
int[][] temp = new int[m][n];
for (int j = 0; j < m; j++) {
for (int k = 0; k < n; k++) {
for (int[] dir : dirs) {
int nm = j + dir[0];
int nn = k + dir[1];
if (nm < 0 || nn < 0 || nm >= m || nn >= n) {
// 如果下一位置翻出去了,就只与前一次移动结果相关
res = (res + cnt[j][k]) % mod;
} else {
temp[nm][nn] = (temp[nm][nn] + cnt[j][k]) % mod;
}
}
}
}
cnt = temp;
}
return res;
}
}