|
| 1 | +/** |
| 2 | + * 576. Out of Boundary Paths |
| 3 | + * https://leetcode.com/problems/out-of-boundary-paths/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is an m x n grid with a ball. The ball is initially at the position [startRow, |
| 7 | + * startColumn]. You are allowed to move the ball to one of the four adjacent cells in |
| 8 | + * the grid (possibly out of the grid crossing the grid boundary). You can apply at most |
| 9 | + * maxMove moves to the ball. |
| 10 | + * |
| 11 | + * Given the five integers m, n, maxMove, startRow, startColumn, return the number of |
| 12 | + * paths to move the ball out of the grid boundary. Since the answer can be very large, |
| 13 | + * return it modulo 109 + 7. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number} m |
| 18 | + * @param {number} n |
| 19 | + * @param {number} maxMove |
| 20 | + * @param {number} startRow |
| 21 | + * @param {number} startColumn |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var findPaths = function(m, n, maxMove, startRow, startColumn) { |
| 25 | + const MOD = 1e9 + 7; |
| 26 | + const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; |
| 27 | + const dp = new Array(maxMove + 1).fill().map(() => { |
| 28 | + return new Array(m).fill().map(() => new Array(n).fill(-1)); |
| 29 | + }); |
| 30 | + |
| 31 | + return solve(maxMove, startRow, startColumn); |
| 32 | + |
| 33 | + function solve(moves, row, col) { |
| 34 | + if (row < 0 || row >= m || col < 0 || col >= n) return 1; |
| 35 | + if (moves === 0) return 0; |
| 36 | + if (dp[moves][row][col] !== -1) return dp[moves][row][col]; |
| 37 | + |
| 38 | + let paths = 0; |
| 39 | + for (const [dr, dc] of directions) { |
| 40 | + paths = (paths + solve(moves - 1, row + dr, col + dc)) % MOD; |
| 41 | + } |
| 42 | + return dp[moves][row][col] = paths; |
| 43 | + } |
| 44 | +}; |
0 commit comments