Problem · Array
Maximum Number of Fish in a Grid
Learn this problemProblem statement
You are given a zero-indexed integer matrix grid. A cell with value 0 is land; a positive cell is water containing that many fish.
A fisher may start at any water cell, catch all fish in the current cell, and move any number of times to an orthogonally adjacent water cell. Return the maximum number of fish obtainable by choosing the starting cell optimally, or 0 when the grid contains no water cell.
Function
findMaxFish(grid: int[][]) → intExamples
Example 1
grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]]return = 7The water cells containing 3 and 4 on the right are connected, giving a component total of 7.
Example 2
grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]]return = 1The two water cells are disconnected and each contains one fish, so the best component has total 1.
Example 3
grid = [[5,1,0],[0,2,3]]return = 11All four positive cells are joined orthogonally, so the component totals 5 + 1 + 2 + 3 = 11.
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 100 <= grid[i][j] <= 10