2658. Maximum Number of Fish in a Grid #1236
-
Topics: You are given a 0-indexed 2D matrix
A fisher can start at any water cell
Return the maximum number of fish the fisher can catch if he chooses his starting cell optimally, or An adjacent cell of the cell Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem is to find the maximum number of fish that a fisher can catch by starting at any water cell in a grid. The fisher can catch fish at the current cell and move to any adjacent water cell (up, down, left, or right) repeatedly. Key Points:
Approach:
Plan:
Let's implement this solution in PHP: 2658. Maximum Number of Fish in a Grid <?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function findMaxFish($grid) {
$rows = count($grid);
$cols = count($grid[0]);
$visited = array_fill(0, $rows, array_fill(0, $cols, false));
$directions = [
[-1, 0], // up
[1, 0], // down
[0, -1], // left
[0, 1] // right
];
$maxFish = 0;
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
if ($grid[$i][$j] > 0 && !$visited[$i][$j]) {
$maxFish = max($maxFish, dfs($i, $j, $grid, $visited, $rows, $cols, $directions));
}
}
}
return $maxFish;
}
/**
* Helper function for DFS
* @param $r
* @param $c
* @param $grid
* @param $visited
* @param $rows
* @param $cols
* @param $directions
* @return array|bool|int|int[]|mixed|null
*/
function dfs($r, $c, &$grid, &$visited, $rows, $cols, $directions) {
if ($r < 0 || $c < 0 || $r >= $rows || $c >= $cols || $grid[$r][$c] == 0 || $visited[$r][$c]) {
return 0;
}
$visited[$r][$c] = true;
$fishCount = $grid[$r][$c];
foreach ($directions as $dir) {
$fishCount += dfs($r + $dir[0], $c + $dir[1], $grid, $visited, $rows, $cols, $directions);
}
return $fishCount;
}
// Example 1
grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]];
echo getMaxFish($grid); // Output: 7
// Example 2
$grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]];
echo getMaxFish($grid); // Output: 1
?> Explanation:DFS Implementation:
Steps:
Example Walkthrough:Example Input:$grid = [
[0, 2, 1, 0],
[4, 0, 0, 3],
[1, 0, 0, 4],
[0, 3, 2, 0]
]; Execution:
Time Complexity:
Output for Examples:
The solution efficiently uses DFS to explore connected components of water cells and calculates the maximum fish catchable by a fisher starting from any water cell. This approach ensures optimal exploration and works well for the given constraints. |
Beta Was this translation helpful? Give feedback.
The problem is to find the maximum number of fish that a fisher can catch by starting at any water cell in a grid. The fisher can catch fish at the current cell and move to any adjacent water cell (up, down, left, or right) repeatedly.
Key Points:
0
) or water (value >0
).Approach: