|
| 1 | +/** |
| 2 | + * 741. Cherry Pickup |
| 3 | + * https://leetcode.com/problems/cherry-pickup/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an n x n grid representing a field of cherries, each cell is one of three |
| 7 | + * possible integers. |
| 8 | + * - 0 means the cell is empty, so you can pass through, |
| 9 | + * - 1 means the cell contains a cherry that you can pick up and pass through, or |
| 10 | + * - -1 means the cell contains a thorn that blocks your way. |
| 11 | + * |
| 12 | + * Return the maximum number of cherries you can collect by following the rules below: |
| 13 | + * - Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through |
| 14 | + * valid path cells (cells with value 0 or 1). |
| 15 | + * - After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path |
| 16 | + * cells. |
| 17 | + * - When passing through a path cell containing a cherry, you pick it up, and the cell becomes |
| 18 | + * an empty cell 0. |
| 19 | + * - If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[][]} grid |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var cherryPickup = function(grid) { |
| 27 | + const n = grid.length; |
| 28 | + const dp = Array.from({ length: n }, () => |
| 29 | + Array.from({ length: n }, () => |
| 30 | + new Array(2 * n - 1).fill(-1)) |
| 31 | + ); |
| 32 | + |
| 33 | + if (grid[0][0] === -1) return 0; |
| 34 | + dp[0][0][0] = grid[0][0]; |
| 35 | + |
| 36 | + for (let t = 1; t <= 2 * n - 2; t++) { |
| 37 | + for (let x1 = Math.max(0, t - n + 1); x1 <= Math.min(n - 1, t); x1++) { |
| 38 | + for (let x2 = Math.max(0, t - n + 1); x2 <= Math.min(n - 1, t); x2++) { |
| 39 | + const y1 = t - x1; |
| 40 | + const y2 = t - x2; |
| 41 | + |
| 42 | + if (grid[x1][y1] === -1 || grid[x2][y2] === -1) continue; |
| 43 | + |
| 44 | + const cherries = grid[x1][y1] + (x1 === x2 ? 0 : grid[x2][y2]); |
| 45 | + let maxPrev = -1; |
| 46 | + |
| 47 | + for (const px1 of [x1 - 1, x1]) { |
| 48 | + for (const px2 of [x2 - 1, x2]) { |
| 49 | + if (px1 >= 0 && px2 >= 0 && dp[px1][px2][t - 1] >= 0) { |
| 50 | + maxPrev = Math.max(maxPrev, dp[px1][px2][t - 1]); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + if (maxPrev >= 0) { |
| 56 | + dp[x1][x2][t] = maxPrev + cherries; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return dp[n - 1][n - 1][2 * n - 2] < 0 ? 0 : dp[n - 1][n - 1][2 * n - 2]; |
| 63 | +}; |
0 commit comments