Problem Description
Given a grid representing a gold mine, find the maximum amount of gold you can collect. You can start and stop at any cell that contains gold, move up, down, left, or right, and every time you step into a cell you collect its gold. You cannot revisit a cell and cannot step on a cell with 0 gold.
Key Insights
- Use Depth First Search (DFS) with backtracking to explore all possible paths.
- Since you cannot revisit a cell, mark a cell as visited temporarily to avoid cycles.
- Start DFS from each cell containing gold to cover all potential paths.
- The small grid size and limited gold cells (at most 25) make the recursive approach feasible.
- Backtracking is crucial: restore the cell's gold after exploring each path to allow other paths to use the cell.
Space and Time Complexity
Time Complexity: Exponential in the worst-case (O(4^(number of gold cells))) due to exploring all paths. Space Complexity: O(m * n) for the recursion stack in the worst-case scenario.
Solution
The solution uses DFS with backtracking. For each cell with positive gold, initiate a DFS that:
- Collects the gold and marks the cell as visited (by setting it to 0).
- Recursively explores all four adjacent cells that are within bounds and contain gold.
- Updates a global maximum sum with the running total.
- Restores the cell’s original gold value on returning (backtracking) to allow exploration of other paths. This approach ensures every path is considered, and the best outcome is recorded.