Leetcode #1219: Path with Maximum Gold
In this guide, we solve Leetcode #1219 Path with Maximum Gold in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Backtracking, Matrix
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
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.
Python Solution
class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
if not (0 <= i < m and 0 <= j < n and grid[i][j]):
return 0
v = grid[i][j]
grid[i][j] = 0
ans = max(dfs(i + a, j + b) for a, b in pairwise(dirs)) + v
grid[i][j] = v
return ans
m, n = len(grid), len(grid[0])
dirs = (-1, 0, 1, 0, -1)
return max(dfs(i, j) for i in range(m) for j in range(n))
Complexity
The time complexity is , where is the maximum length of each path. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.