Problem 1219

Abstract / Summary

Find the maximum gold collected by moving from a starting cell in a grid to adjacent cells without revisiting any cell.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1219.py

class Solution:
    def getMaximumGold(self, grid: List[List[int]]) -> int:
        width  = len(grid[0])
        height = len(grid)

        def deeper(x, y):
            # outside
            if x < 0 or x >= width or y < 0 or y >= height:
                return 0
            # no gold, stop
            found = grid[y][x]
            if found == 0:
                return 0

            # take that gold
            grid[y][x] = 0

            # keep digging
            best =           deeper(x - 1, y)
            best = max(best, deeper(x + 1, y))
            best = max(best, deeper(x, y - 1))
            best = max(best, deeper(x, y + 1))

            # restore gold
            grid[y][x] = found

            return found + best

        result = 0
        for y in range(height):
            for x in range(width):
                result = max(result, deeper(x, y))
        return result
33 lines | 935 bytes | submitted January 7, 2024 | GitHub   22% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method getMaximumGold that receives a two-dimensional list grid. Each cell contains a non-negative integer representing the amount of gold in that location, or zero if the cell is empty. The method computes the maximum total amount of gold that can be collected by starting from any cell that contains gold and moving only in the four orthogonal directions (up, down, left, right). A cell may be visited at most once during a single path, and the search terminates when it reaches a cell with no gold or the border of the grid. The algorithm explores all possible starting positions and returns the highest sum found.

Key Steps

Determining Grid Dimensions

width  = len(grid[0])
height = len(grid)

The code extracts the number of columns (width) and rows (height) once, allowing subsequent index calculations to use constant-time look-ups.

Depth-First Search Helper

A nested function deeper(x, y) performs a recursive depth-first search from the coordinates (x, y).

def deeper(x, y):
    # outside
    if x < 0 or x >= width or y < 0 or y >= height:
        return 0
    # no gold, stop
    found = grid[y][x]
    if found == 0:
        return 0

The first two conditional blocks guard against two edge conditions: stepping outside the grid bounds and stepping onto a cell that contains no gold. In both cases the recursion terminates early, returning zero contribution for that branch.

Collecting Gold and Marking the Cell

    # take that gold
    grid[y][x] = 0

The current cell’s gold value is stored in found, then the cell is temporarily set to zero. This in-place marking serves as a visitation flag, ensuring that the same cell cannot be revisited within the current path without needing an auxiliary visited matrix.

Exploring Adjacent Cells

    # keep digging
    best =           deeper(x - 1, y)
    best = max(best, deeper(x + 1, y))
    best = max(best, deeper(x, y - 1))
    best = max(best, deeper(x, y + 1))

The function recursively explores the four neighboring positions, keeping track of the maximum gold that can be gathered from any of those directions. The use of max after each call aggregates the best continuation from the current cell.

Restoring the Cell State

    # restore gold
    grid[y][x] = found

After all recursive calls return, the original gold amount is written back to the cell. This backtracking step restores the grid to its initial state, allowing other starting positions to treat the cell as unvisited.

Returning the Accumulated Value

    return found + best

The function adds the gold taken from the current cell (found) to the best amount obtainable from the subsequent moves (best) and returns this sum to the caller.

Iterating Over All Starting Positions

result = 0
for y in range(height):
    for x in range(width):
        result = max(result, deeper(x, y))
return result

Two nested loops enumerate every coordinate in the grid. For each cell, deeper is invoked, and the global maximum result is updated with the best path that originates from that cell.

Edge Cases Handled

The recursion explicitly checks for coordinates that lie outside the rectangular bounds, preventing index errors when the search reaches the perimeter. Cells that contain zero gold are treated as dead ends; the early return ensures that paths do not continue through empty cells. By resetting a visited cell back to its original value after exploring all branches, the algorithm correctly handles overlapping paths that share cells only when they belong to distinct starting points. The initial result value of zero also covers the scenario where the entire grid contains no gold, guaranteeing that the method returns zero in that case.

Performance Optimizations

The implementation avoids allocating additional data structures for tracking visited cells. Instead, it leverages in-place modification of the input grid, marking a cell as visited by setting its value to zero and restoring it after recursion. This technique reduces memory overhead and improves cache locality because the same grid array is reused throughout the search. Early termination checks for out-of-bounds coordinates and zero-gold cells prune the recursion tree, preventing unnecessary deeper calls. By computing the maximum of the four directional results incrementally, the code eliminates the need for an intermediate collection of all four values, thereby saving temporary storage and reducing the number of function calls. The outer loops iterate over each cell exactly once, and the recursive depth-first search explores only viable paths, ensuring that the algorithm focuses computational effort on meaningful branches.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big field of grass that is marked out like a grid of squares. Some of these squares have hidden treasure buried inside them, while others are empty. Think of this code as a tiny robot helping to find the best path to dig up as much treasure as possible.

The robot starts by looking at every single square in the field to decide where to begin. Once it picks a starting square, it looks at the spot to see if there is any treasure. If the spot is empty, the robot stops and tries a different path. If there is treasure, the robot picks it up and remembers how much it found. After taking the treasure, the spot becomes empty for a moment so the robot does not try to dig there again.

Then the robot looks in all four directions, like north, south, east, and west, to see if there is more treasure nearby. It moves to the next pile of treasure and keeps exploring until it hits a wall or an empty spot. Once the robot finishes exploring a path, it pretends to put the treasure back so that other paths can use those same squares to see if they can find even more.

The robot does this over and over again for every starting point in the grid. It compares all the different adventures it took to see which path led to the biggest pile of treasure. By checking every single way to walk through the grid, the robot makes sure it finds the absolute best amount of gold hidden in the ground.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.35 | σ = 0.96

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Go TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
martianoff Scala
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
martianoff Scala
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
30 links | 18 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   January 7, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality