The Maximum Number of Fish in a Grid coding problem gives you a 2D grid where each cell either contains 0 (water) or a positive number (land with fish). Starting from any land cell, you can move to adjacent land cells (4-directionally) and collect all fish. You want to find the maximum total fish collectible from any single connected land component.
Microsoft, Meta, Amazon, and Google include this problem as a clean BFS/DFS connected component problem with a value-aggregation twist. It tests whether candidates can correctly enumerate connected components in a grid and aggregate values. It is a natural extension of the island-counting problem family, adding the requirement to maximize sum rather than count components.
BFS or DFS flood-fill: For each unvisited land cell, run a BFS/DFS to explore the entire connected component, summing all fish values. Mark cells as visited (set to 0 or use a separate visited array). Track the maximum sum seen across all components. Time: O(mn), Space: O(mn) for the visited set or call stack.
Union-Find is also applicable: unite adjacent land cells, track component sums, find the maximum.
Grid:
0 2 1 0
4 0 0 3
1 0 0 4
0 3 2 0
For the Array Matrix Union Find Breadth-First Search Depth-First Search interview pattern, this problem is an excellent template for "max value connected component" problems. Implement the DFS version as a recursive helper that returns the sum of the current component, then iterate over all cells calling it on unvisited land cells. Practice this template for grids with islands, connected components, and value aggregation.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Closed Islands | Medium | Solve | |
| Detect Cycles in 2D Grid | Medium | Solve | |
| Number of Enclaves | Medium | Solve | |
| Count Sub Islands | Medium | Solve | |
| Surrounded Regions | Medium | Solve |