Path with Maximum Gold

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; from your position, you can walk one step to the left, right, up, or down; you cannot visit the same cell more than once; never visit a cell with 0 gold; you can start and stop collecting gold from any position in the grid that has some gold.

30:00

Path with Maximum Gold
medium
Free written solution
Topics
Companies

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; from your position, you can walk one step to the left, right, up, or down; you cannot visit the same cell more than once; never visit a cell with 0 gold; you can start and stop collecting gold from any position in the grid that has some gold.

Example 1:
Input: {"grid":[[0,6,0],[5,8,7],[0,9,0]]}
Output: 24
Constraints:
  • m==grid.lengthm == \text{grid.length}, n==grid[i].lengthn == \text{grid}[i].\text{length}

  • 1≤m,n≤151 \leq m, n \leq 15

  • 0≤grid[i][j]≤1000 \leq \text{grid}[i][j] \leq 100

  • There are at most 25 cells containing gold.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[0,6,0],[5,8,7],[0,9,0]]}

5 cells hold gold. Any of them can be a start, so try each one and walk every path that never repeats a cell or steps on 0.

this path

0

start

-

best

0

6
5
8
7
9
bright cells + brown line: current pathgreen dashes: best path so farS: start, ✓: start finished
Variables
VariableValue
m3
n3
best0
DepthFunction Call
Stack empty
0/52