Path with Maximum Gold (LeetCode 1219): Solution and Explanation
A grid holds gold amounts, with 0 for empty cells. Walking up, down, left or right, never revisiting a cell and never stepping on 0, find the path that collects the most gold. You may start and stop on any gold cell.
Intuition
This is a longest-path problem, and longest simple paths have no greedy or DP shortcut on a general grid. What saves us is the constraint: at most 25 cells hold gold, so exhaustive search is affordable.
The search is a DFS that walks one path at a time. Entering a cell collects its gold and blocks the cell so the path cannot loop back. Setting it to 0 in place does both jobs at once, because the rule already forbids stepping on 0.
When the DFS returns from a cell it must put the gold back. Another path, from a different start or through a different neighbour, may still want to pass through it. That mark, recurse, restore pattern is what makes it backtracking.
Since the best path can begin anywhere, run the DFS from every gold cell and keep the largest total. Each DFS returns the cell's own gold plus the best of its four neighbour results.
Approach: Backtracking DFS from each gold cell
- Set
best = 0. - For every cell with gold, call
dfs(r, c)and updatebestwith its result. - In
dfs, return 0 if the cell is outside the grid or holds 0. - Save
gold = grid[r][c]and set the cell to 0 so the current path cannot revisit it. - Recurse into the four neighbours and keep the largest return value as
most. - Restore
grid[r][c] = goldand returngold + most.
Step-by-step example
grid = [[0,6,0],[5,8,7],[0,9,0]]
- Gold sits in a plus shape: 6 on top, 5, 8, 7 across the middle, 9 at the bottom.
- Starting from 6: the only move is to 8, then to 5, 7 or 9. The best continuation is 9, giving 6 + 8 + 9 = 23.
- Starting from 5: 5 -> 8 -> 9 gives 22.
- Starting from 8: once 8 is used, each neighbour is a dead end, so the path takes one step and the best is 8 + 9 = 17.
- Starting from 7: 7 -> 8 -> 9 gives 24, the best so far.
- Starting from 9: 9 -> 8 -> 7 also gives 24. Every start is tried, so the answer is 24.
Code: Python, Java, C++
1class Solution:
2 def getMaximumGold(self, grid: List[List[int]]) -> int:
3 m, n = len(grid), len(grid[0])
4 best = 0
5
6 def dfs(r, c):
7 if r < 0 or r >= m or c < 0 or c >= n or grid[r][c] == 0:
8 return 0
9 gold = grid[r][c]
10 grid[r][c] = 0
11 most = 0
12 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
13 most = max(most, dfs(r + dr, c + dc))
14 grid[r][c] = gold
15 return gold + most
16
17 for r in range(m):
18 for c in range(n):
19 if grid[r][c] != 0:
20 best = max(best, dfs(r, c))
21 return best1class Solution {
2 private static final int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
3
4 public int getMaximumGold(int[][] grid) {
5 int best = 0;
6 for (int r = 0; r < grid.length; r++) {
7 for (int c = 0; c < grid[0].length; c++) {
8 if (grid[r][c] != 0) {
9 best = Math.max(best, dfs(grid, r, c));
10 }
11 }
12 }
13 return best;
14 }
15
16 private int dfs(int[][] grid, int r, int c) {
17 if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == 0) return 0;
18 int gold = grid[r][c];
19 grid[r][c] = 0;
20 int most = 0;
21 for (int[] d : DIRS) {
22 most = Math.max(most, dfs(grid, r + d[0], c + d[1]));
23 }
24 grid[r][c] = gold;
25 return gold + most;
26 }
27}1class Solution {
2public:
3 int getMaximumGold(vector<vector<int>>& grid) {
4 int best = 0;
5 for (int r = 0; r < (int)grid.size(); r++) {
6 for (int c = 0; c < (int)grid[0].size(); c++) {
7 if (grid[r][c] != 0) {
8 best = max(best, dfs(grid, r, c));
9 }
10 }
11 }
12 return best;
13 }
14
15private:
16 int dfs(vector<vector<int>>& grid, int r, int c) {
17 if (r < 0 || r >= (int)grid.size() || c < 0 || c >= (int)grid[0].size() || grid[r][c] == 0) return 0;
18 int gold = grid[r][c];
19 grid[r][c] = 0;
20 int most = 0;
21 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
22 for (auto& d : dirs) {
23 most = max(most, dfs(grid, r + d[0], c + d[1]));
24 }
25 grid[r][c] = gold;
26 return gold + most;
27 }
28};Time and space complexity
O(k * 3^k)
There are k gold cells and each can start a search. After the first step every cell has at most three unvisited directions, so one search explores at most about 3^k paths. In practice the grid shape cuts this far lower.
O(k)
The recursion depth is the path length, which is at most k. Marking cells in place needs no extra visited set.
Other approaches
Separate visited set (time O(k * 3^k), space O(m * n))
Keep a boolean grid or a set of visited coordinates instead of overwriting the cell with 0. It leaves the input untouched at the cost of extra memory and lookups.
Bitmask DP over gold cells (time O(2^k * k^2), space O(2^k * k))
Index the k gold cells and let dp[mask][v] be the best total of a path that visits exactly the cells in mask and ends at v. It is exponential in k as well and uses far more memory, so it only pays off when many paths share the same visited set.
Common mistakes
- Forgetting to restore the cell after the recursion, which permanently removes gold that other paths need.
- Only starting from cells on the border or from the largest cell. The best path can start anywhere.
- Adding the neighbours' results together instead of taking the maximum. A path continues in only one direction.
- Starting the DFS from cells with 0, which the rules forbid.
Frequently asked questions
Why is brute force fast enough here?
The problem caps the number of gold cells at 25, and grid paths branch at most three ways after the first step. The real number of simple paths through so few cells stays small enough for the search.
Is it safe to modify the input grid?
Yes, as long as every change is undone before the DFS returns. When the main loop finishes, the grid is exactly as it started.
Can a common speedup skip some starting cells?
One known trick is to start only from cells with at most two gold neighbours, since a best path can always be extended to end at such a cell. It is optional; the plain version already fits the limits.