Home >Backend Development >PHP Tutorial >Maximum Number of Fish in a Grid
2658. Maximum Number of Fish in a Grid
Difficulty: Medium
Topics: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix
You are given a 0-indexed 2D matrix grid of size m x n, where (r, c) represents:
A fisher can start at any water cell (r, c) and can do the following operations any number of times:
Return the maximum number of fish the fisher can catch if he chooses his starting cell optimally, or 0 if no water cell exists.
An adjacent cell of the cell (r, c), is one of the cells (r, c 1), (r, c - 1), (r 1, c) or (r - 1, c) if it exists.
Example 1:
Example 2:
Constraints:
Hint:
Solution:
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.
Let's implement this solution in PHP: 2658. Maximum Number of Fish in a Grid
<?php /** * @param Integer[][] $grid * @return Integer */ function findMaxFish($grid) { ... ... ... /** * go to ./solution.php */ } /** * 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) { ... ... ... /** * go to ./solution.php */ } // 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 ?>
$grid = [ [0, 2, 1, 0], [4, 0, 0, 3], [1, 0, 0, 4], [0, 3, 2, 0] ];
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.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Maximum Number of Fish in a Grid. For more information, please follow other related articles on the PHP Chinese website!