1219. Path with Maximum Gold #257
-
Topics: In a gold mine Return the maximum amount of gold you can collect under the conditions:
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The "Path with Maximum Gold" problem is a typical backtracking problem where we need to find the maximum amount of gold we can collect in a grid-based mine. The challenge is to explore different paths under certain conditions like not revisiting any cell and avoiding cells that contain 0 gold. This problem requires recursive exploration of possible paths, which is where the backtracking approach comes in. Key Points
Approach
Plan
Let's implement this solution in PHP: 1219. Path with Maximum Gold <?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function getMaximumGold($grid) {
$m = count($grid);
$n = count($grid[0]);
$dfs = function ($i, $j) use (&$dfs, $m, $n, &$grid) {
if ($i < 0 || $i >= $m || $j < 0 || $j >= $n || !$grid[$i][$j]) {
return 0;
}
$v = $grid[$i][$j];
$grid[$i][$j] = 0;
$ans = $v + max([$dfs($i - 1, $j), $dfs($i + 1, $j), $dfs($i, $j - 1), $dfs($i, $j + 1)]);
$grid[$i][$j] = $v;
return $ans;
};
$ans = 0;
for ($i = 0; $i < $m; ++$i) {
for ($j = 0; $j < $n; ++$j) {
$ans = max($ans, $dfs($i, $j));
}
}
return $ans;
}
// Example usage:
$grid1 = [[0,6,0],[5,8,7],[0,9,0]];
$grid2 = grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]];
echo getMaximumGold($grid1) . "\n"; // Output: 24
echo getMaximumGold($grid2) . "\n"; // Output: 28
?> Explanation:The DFS function works as follows:
Example WalkthroughExample 1: grid = [
[0,6,0],
[5,8,7],
[0,9,0]
]
Example 2: grid = [
[1,0,7],
[2,0,6],
[3,4,5],
[0,3,0],
[9,0,20]
]
Time ComplexityThe time complexity is O(m * n), where
Output for ExampleFor the example inputs:
grid = [
[0,6,0],
[5,8,7],
[0,9,0]
] Output:
grid = [
[1,0,7],
[2,0,6],
[3,4,5],
[0,3,0],
[9,0,20]
] Output: The "Path with Maximum Gold" problem is a great exercise in using DFS with backtracking. It requires careful exploration of all possible paths in a grid while ensuring we do not revisit cells. The approach demonstrated here ensures we can find the maximum amount of gold efficiently by using recursion and backtracking. The time complexity of O(m * n) makes the solution feasible even for the largest grid sizes, within the given constraints. |
Beta Was this translation helpful? Give feedback.
The "Path with Maximum Gold" problem is a typical backtracking problem where we need to find the maximum amount of gold we can collect in a grid-based mine. The challenge is to explore different paths under certain conditions like not revisiting any cell and avoiding cells that contain 0 gold. This problem requires recursive exploration of possible paths, which is where the backtracking approach comes in.
Key Points