#1219

Path with Maximum Gold

Medium Grid DFS backtracking

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Each grid cell holds some gold (0 means you can't step there). Starting anywhere, walk up/down/left/right without revisiting a cell and collect gold. Return the most gold possible.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: walk through gold cells without revisiting; collect the most gold.

Why this works: try each gold cell as a start, DFS in four directions, and restore the cell when backtracking.

Example: [[0,6,0],[5,8,7],[0,9,0]]

9 → 8 → 7 = 24 (best)

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Not restoring the cell's gold, which corrupts later starts.

Solve on LeetCode ↗
Complexity
  • Time: O(G · 3^G), G = gold cells (at most 25).
  • Space: O(G).
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon