Maximum Number of Fish in a Grid - Problem

Imagine you're a fisher exploring a vast archipelago represented by a 2D grid! Each cell in this grid can be either:

  • 0 - A land cell where you cannot go
  • positive integer - A water cell containing that many fish

As an expert fisher, you can:

  • ๐ŸŽฃ Catch all fish in your current water cell
  • ๐Ÿšค Move to adjacent water cells (up, down, left, right)

Your mission: Choose the optimal starting position to maximize your total catch! You can only move between connected water cells, so choose wisely.

Goal: Return the maximum number of fish you can catch, or 0 if there are no water cells.

Input & Output

example_1.py โ€” Basic Connected Water
$ Input: grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]]
โ€บ Output: 7
๐Ÿ’ก Note: The fisher can start at (1,0) and catch 4 fish, then move to (2,0) and catch 1 fish, then move to (3,1) and catch 3 fish. However, they cannot reach (3,2) or other water cells from this position. The optimal path gives 4+1 = 5 fish from the left component, but there's a larger component with 7 fish total.
example_2.py โ€” Single Large Component
$ Input: grid = [[1,2,3,0],[0,1,0,0],[0,0,1,0]]
โ€บ Output: 6
๐Ÿ’ก Note: Starting from any cell in the connected water region (containing values 1,2,3), the fisher can catch all fish in this component for a total of 1+2+3 = 6 fish.
example_3.py โ€” No Water Cells
$ Input: grid = [[0,0],[0,0]]
โ€บ Output: 0
๐Ÿ’ก Note: There are no water cells (all cells have value 0), so the fisher cannot catch any fish.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • 0 <= grid[i][j] <= 10

Visualization

Tap to expand
Fisher's Island Hopping Strategy๐Ÿ๏ธ53๐Ÿ๏ธ2๐Ÿ๏ธ๐Ÿ๏ธ41๐Ÿ๏ธ๐Ÿ๏ธ๐Ÿ๏ธIsland Chain 1Total: 5 + 3 = 8 fishIsland Chain 2Total: 4 fishIsland Chain 3Total: 2 + 1 = 3 fish๐Ÿšค Fisher's Strategy:1. Identify all separate island chains2. Calculate total fish in each chain3. Choose the richest chain: Chain 1 (8 fish)4. Optimal result: 8 fish ๐ŸŸ
Understanding the Visualization
1
Survey the Waters
Look at the grid to identify all water cells (positive values) and land cells (zeros)
2
Find Island Chains
Each connected group of water cells forms a separate island chain
3
Explore Each Chain
Use DFS/BFS to fully explore each connected water region once
4
Choose Best Chain
Return the total fish from the richest island chain
Key Takeaway
๐ŸŽฏ Key Insight: Instead of trying every starting position, we identify connected components once and find the richest one. This reduces time complexity from O(mยฒnยฒ) to O(mn)!
Asked in
Amazon 25 Microsoft 18 Google 15 Meta 12
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen