|
| 1 | +/** |
| 2 | + * 1301. Number of Paths with Max Score |
| 3 | + * https://leetcode.com/problems/number-of-paths-with-max-score/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a square board of characters. You can move on the board starting at the bottom |
| 7 | + * right square marked with the character 'S'. |
| 8 | + * |
| 9 | + * You need to reach the top left square marked with the character 'E'. The rest of the squares |
| 10 | + * are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move |
| 11 | + * you can go up, left or up-left (diagonally) only if there is no obstacle there. |
| 12 | + * |
| 13 | + * Return a list of two integers: the first integer is the maximum sum of numeric characters you |
| 14 | + * can collect, and the second is the number of such paths that you can take to get that maximum |
| 15 | + * sum, taken modulo 10^9 + 7. |
| 16 | + * |
| 17 | + * In case there is no path, return [0, 0]. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {string[]} board |
| 22 | + * @return {number[]} |
| 23 | + */ |
| 24 | +var pathsWithMaxScore = function(board) { |
| 25 | + const n = board.length; |
| 26 | + const mod = 1000000007; |
| 27 | + const dp = Array.from({ length: n }, () => |
| 28 | + new Array(n).fill([-Infinity, 0]) |
| 29 | + ); |
| 30 | + |
| 31 | + dp[n-1][n-1] = [0, 1]; |
| 32 | + |
| 33 | + for (let row = n-1; row >= 0; row--) { |
| 34 | + for (let col = n-1; col >= 0; col--) { |
| 35 | + if (board[row][col] === 'X') { |
| 36 | + dp[row][col] = [-Infinity, 0]; |
| 37 | + continue; |
| 38 | + } |
| 39 | + |
| 40 | + if (row === n-1 && col === n-1) continue; |
| 41 | + |
| 42 | + const value = board[row][col] === 'E' ? 0 : Number(board[row][col]); |
| 43 | + const directions = [[0, 1], [1, 0], [1, 1]]; |
| 44 | + |
| 45 | + for (const [dr, dc] of directions) { |
| 46 | + const nextRow = row + dr; |
| 47 | + const nextCol = col + dc; |
| 48 | + |
| 49 | + if (nextRow >= n || nextCol >= n) continue; |
| 50 | + if (dp[nextRow][nextCol][1] === 0) continue; |
| 51 | + |
| 52 | + const score = dp[nextRow][nextCol][0] + value; |
| 53 | + if (score > dp[row][col][0]) { |
| 54 | + dp[row][col] = [score, dp[nextRow][nextCol][1]]; |
| 55 | + } else if (score === dp[row][col][0]) { |
| 56 | + dp[row][col][1] = (dp[row][col][1] + dp[nextRow][nextCol][1]) % mod; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return dp[0][0][1] === 0 ? [0, 0] : dp[0][0]; |
| 63 | +}; |
0 commit comments