1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { final int MOD = (int) Math.pow(10, 9) + 7; long[][][] memo; public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) { memo = new long[m][n][maxMove]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ for(int k = 0; k < maxMove; k++){ memo[i][j][k] = -1; } } } return (int) dfs(m, n, maxMove, startRow, startColumn); } private long dfs(int m, int n, int maxMove, int startRow, int startColumn){ if(startRow < 0 || startRow >= m || startColumn < 0 || startColumn >= n) return 1; if(maxMove == 0) return 0; maxMove--; if(memo[startRow][startColumn][maxMove] != -1) return memo[startRow][startColumn][maxMove]; long left = dfs(m, n, maxMove, startRow-1, startColumn); long right = dfs(m, n, maxMove, startRow+1, startColumn); long up = dfs(m, n, maxMove, startRow, startColumn+1); long down = dfs(m, n, maxMove, startRow, startColumn-1);
memo[startRow][startColumn][maxMove] = (left + right + up + down) % MOD; return memo[startRow][startColumn][maxMove]; } }
|