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
Maximum Number of Fish in a Grid INPUT 0 2 1 0 4 0 0 3 1 0 0 4 0 3 2 0 Water (fish) Land [[0,2,1,0],[4,0,0,3], [1,0,0,4],[0,3,2,0]] ALGORITHM (DFS) 1 Find Water Cells Scan grid for cells > 0 2 DFS from Each Explore connected water 3 Sum Fish Count Add fish in component 4 Track Maximum Keep best total found Best Component: 3 4 0 3 + 4 = 7 FINAL RESULT 3 4 Output: 7 OK - Maximum! Key Insight: This is a connected components problem. Each water region forms an "island" of fish. Use DFS to explore each component, sum all fish values, and track the maximum sum across all components. TutorialsPoint - Maximum Number of Fish in a Grid | DFS Approach
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