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 gopositive 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
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)!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code