|
| 1 | +/** |
| 2 | + * 1219. Path with Maximum Gold |
| 3 | + * https://leetcode.com/problems/path-with-maximum-gold/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * In a gold mine grid of size m x n, each cell in this mine has an integer representing the |
| 7 | + * amount of gold in that cell, 0 if it is empty. |
| 8 | + * |
| 9 | + * Return the maximum amount of gold you can collect under the conditions: |
| 10 | + * - Every time you are located in a cell you will collect all the gold in that cell. |
| 11 | + * - From your position, you can walk one step to the left, right, up, or down. |
| 12 | + * - You can't visit the same cell more than once. |
| 13 | + * - Never visit a cell with 0 gold. |
| 14 | + * - You can start and stop collecting gold from any position in the grid that has some gold. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[][]} grid |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var getMaximumGold = function(grid) { |
| 22 | + const rows = grid.length; |
| 23 | + const cols = grid[0].length; |
| 24 | + let maxGold = 0; |
| 25 | + |
| 26 | + for (let i = 0; i < rows; i++) { |
| 27 | + for (let j = 0; j < cols; j++) { |
| 28 | + if (grid[i][j] !== 0) { |
| 29 | + exploreGold(i, j, 0); |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + return maxGold; |
| 35 | + |
| 36 | + function exploreGold(row, col, currentGold) { |
| 37 | + if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] === 0) { |
| 38 | + maxGold = Math.max(maxGold, currentGold); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + const goldHere = grid[row][col]; |
| 43 | + grid[row][col] = 0; |
| 44 | + |
| 45 | + exploreGold(row - 1, col, currentGold + goldHere); |
| 46 | + exploreGold(row + 1, col, currentGold + goldHere); |
| 47 | + exploreGold(row, col - 1, currentGold + goldHere); |
| 48 | + exploreGold(row, col + 1, currentGold + goldHere); |
| 49 | + |
| 50 | + grid[row][col] = goldHere; |
| 51 | + } |
| 52 | +}; |
0 commit comments