Problem Description
Given a grid representing water cells (with a positive number indicating the number of fish) and land cells (zero), determine the maximum number of fish a fisher can catch by starting at some water cell and moving to adjacent water cells (up, down, left, right). The goal is to compute the sum of fish over a connected component of water cells, and the fisher collects all fish in that component by visiting each cell once. Return 0 if no water cell exists.
Key Insights
- The problem is about finding the maximum sum over all connected components in the matrix.
- Each water cell (grid value > 0) can be visited, and adjacent cells (up, down, left, right) are only accessible if they are also water cells.
- Flood fill using Depth-First Search (DFS) or Breadth-First Search (BFS) can be employed to traverse each connected component.
- Mark visited cells to avoid double counting.
- Since grid dimensions are small (m, n <= 10), either DFS or BFS is efficient.
Space and Time Complexity
Time Complexity: O(m * n) — Each cell is visited once. Space Complexity: O(m * n) — In the worst case, the recursion stack (for DFS) or queue (for BFS) holds all cells.
Solution
We iterate through each cell in the grid. For every unvisited water cell, we start a DFS (or BFS) that sums all the fish in the connected component. We mark each visited cell to ensure it's not processed again. Finally, the answer is the maximum total fish collected from any connected component. We use a grid traversal, simple recursion (for DFS), and a visited marker (either an auxiliary matrix or in-place modification if allowed).