Maximum Number of Fish in a Grid

Medium Topics Company Tags

In grid, a zero is land and a positive entry is water containing that many fish. Start at any water cell and move through water cells that share an edge: up, down, left, or right. You may revisit cells, but fish in each cell can be collected only once. Collecting fish does not turn water into land. Return the maximum total fish obtainable from one starting cell, or 0 if the grid contains only land.

Hatching marks a connected group with the greatest total number of fish.

Example 1:

Maximum Number of Fish in a Grid, example 1: illustration of the example

Input: grid = [[2,3,0],[0,4,1]]

Output: 10

Explanation: All four water cells are connected through shared edges. Visit them to collect 2 + 3 + 4 + 1 = 10 fish. Land cells do not need to be crossed.

Example 2:

Maximum Number of Fish in a Grid, example 2: illustration of the example

Input: grid = [[5,0],[0,8]]

Output: 8

Explanation: The two water cells touch only diagonally, so travel between them is impossible. Start at the cell containing 8 fish.

Example 3:

Maximum Number of Fish in a Grid, example 3: illustration of the example

Input: grid = [[0,0],[0,0]]

Output: 0

Explanation: Every cell is land. There is no starting water cell, so the answer is 0.

Constraints:

  • 1 <= grid.length <= 10
  • Every row has the same length, between 1 and 10.
  • 0 <= grid[i][j] <= 10


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.