Path with Maximum Gold Problem
Description
LeetCode Problem 1219.
In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
- Every time you are located in a cell you will collect all the gold in that cell.
- From your position, you can walk one step to the left, right, up, or down.
- You can't visit the same cell more than once.
- Never visit a cell with
0gold. - You can start and stop collecting gold from any position in the grid that has some gold.
Example 1:
Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
[5,8,7],
[0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.
Example 2:
Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
[2,0,6],
[3,4,5],
[0,3,0],
[9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 150 <= grid[i][j] <= 100- There are at most 25 cells containing gold.
Solution
Approach: Backtracking DFS
There are at most 25 cells with gold, so we can afford to try every path. Start a depth-first search from every cell; dfs(i, j) returns the most gold on a path that starts at (i, j):
- If
(i, j)is outside the grid or holds no gold (empty, or already on the current path), return0. - Otherwise take its gold, set the cell to
0so the path cannot come back to it, and try the four neighbors. The result is this cell's gold plus the best neighbor result. - Put the gold back before returning, so other paths can use this cell.
Zeroing the cell works as the "visited" mark because cells with 0 gold are forbidden anyway, so no extra visited array is needed. The tricky part is the restore step: without it, one search would wreck the grid for every later start.
The answer is the best dfs(i, j) over all cells (it is 0 if there is no gold at all).
Complexity: O(k · 3k) time in the worst case for k <= 25 gold cells (from each start, every step has at most 3 new directions), plus O(mn) to try every start. Extra space is O(k) for the recursion.
class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def dfs(i: int, j: int) -> int:
# Most gold on a path that starts at (i, j) and never revisits a cell.
if not (0 <= i < m and 0 <= j < n) or grid[i][j] == 0:
return 0
gold = grid[i][j]
grid[i][j] = 0 # mark as visited
best = max(dfs(i - 1, j), dfs(i + 1, j), dfs(i, j - 1), dfs(i, j + 1))
grid[i][j] = gold # backtrack
return gold + best
return max(dfs(i, j) for i in range(m) for j in range(n))