|
1 | 1 | class Solution {
|
2 |
| - private final int MODULUS = 1000000000 + 7; |
3 |
| - |
4 |
| - public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { |
5 |
| - int dp[][] = new int[m][n]; |
6 |
| - dp[startRow][startColumn] = 1; |
7 |
| - int count = 0; |
8 |
| - for (int currMove = 1; currMove <= maxMove; currMove++) { |
9 |
| - int[][] temp = new int[m][n]; |
10 |
| - for (int i = 0; i < m; i++) { |
11 |
| - for (int j = 0; j < n; j++) { |
12 |
| - if (i == m - 1) { |
13 |
| - count = (count + dp[i][j]) % MODULUS; |
14 |
| - } |
15 |
| - if (j == n - 1) { |
16 |
| - count = (count + dp[i][j]) % MODULUS; |
17 |
| - } |
18 |
| - if (i == 0) { |
19 |
| - count = (count + dp[i][j]) % MODULUS; |
20 |
| - } |
21 |
| - if (j == 0) { |
22 |
| - count = (count + dp[i][j]) % MODULUS; |
23 |
| - } |
24 |
| - temp[i][j] = ( |
25 |
| - ((i > 0 ? dp[i - 1][j] : 0) + (i < m - 1 ? dp[i + 1][j] : 0)) % MODULUS + |
26 |
| - ((j > 0 ? dp[i][j - 1] : 0) + (j < n - 1 ? dp[i][j + 1] : 0)) % MODULUS |
27 |
| - ) % MODULUS; |
| 2 | + |
| 3 | + private static final int MOD = 1000_000_007; |
| 4 | + |
| 5 | + public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { |
| 6 | + Integer[][][] dp = new Integer[m][n][maxMove + 1]; |
| 7 | + return findPaths(m, n, maxMove, startRow, startColumn, dp); |
| 8 | + } |
| 9 | + |
| 10 | + public int findPaths(int m, int n, int maxMove, int startRow, int startColumn, Integer[][][] dp) { |
| 11 | + if (startRow == m || startColumn == n || startRow < 0 || startColumn < 0) { |
| 12 | + return 1; |
| 13 | + } |
| 14 | + if (maxMove == 0) { |
| 15 | + return 0; |
| 16 | + } |
| 17 | + if (dp[startRow][startColumn][maxMove] != null) { |
| 18 | + return dp[startRow][startColumn][maxMove]; |
28 | 19 | }
|
29 |
| - } |
30 |
| - dp = temp; |
| 20 | + return dp[startRow][startColumn][maxMove] = ( |
| 21 | + (findPaths(m, n, maxMove - 1, startRow - 1, startColumn, dp) + |
| 22 | + findPaths(m, n, maxMove - 1, startRow + 1, startColumn, dp)) % MOD + |
| 23 | + (findPaths(m, n, maxMove - 1, startRow, startColumn - 1, dp) + |
| 24 | + findPaths(m, n, maxMove - 1, startRow, startColumn + 1, dp)) % MOD) % MOD; |
31 | 25 | }
|
32 |
| - return count; |
33 |
| - } |
34 | 26 | }
|
0 commit comments