Path with Maximum Gold — LeetCode 1219 Python Solution

MediumArrayBacktrackingMatrix
Problem
#1219
Reading time
3 min

The problem

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.

Example

Input
grid = [[0,6,0],[5,8,7],[0,9,0]]
Output
24
Explanation
[[0,6,0],

Python solution

Python
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

MeasureComplexity
TimeO(m \times n \times 3^k), where k is the maximum length of each path
SpaceO(m \times n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1219. Path with Maximum Gold is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1219. Path with Maximum Gold?
LeetCode 1219. Path with Maximum Gold is rated Medium on LeetCode.
What is the time complexity of LeetCode 1219. Path with Maximum Gold?
The Python solution on this page runs in O(m \times n \times 3^k), where k is the maximum length of each path.
What is the space complexity of LeetCode 1219. Path with Maximum Gold?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1219. Path with Maximum Gold cover?
LeetCode 1219. Path with Maximum Gold is tagged Array, Backtracking and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview