 ✅ Maximum Number of Fish in a Grid | JS🔥 | beats 99%🚀 | 🚀highly optimised & easy to understand ✅
Intuition
To solve the Maximum Number of Fish in a Grid problem, we can use Depth-First Search (DFS) to explore the grid.
Approach
Start from every water cell (
# Intuition
- To solve the Maximum Number of Fish in a Grid problem, we can use Depth-First Search (DFS) to explore the grid.
# Approach
- Start from every water cell (grid[i][j] > 0).
- Use DFS to traverse all reachable water cells and collect the fish.
- Keep track of the maximum number of fish collected starting from any cell.
> **DFS Traversal:**
- Starting from any water cell (grid[r][c] > 0), recursively visit all adjacent water cells, collecting the fish and marking the cells as visited (grid[r][c] = 0).
> **Iterate Through Grid:**
- For every water cell in the grid, start a DFS and calculate the total fish collected. Update the maxFish if this value is greater than the current maximum.
# Complexity
> **Time complexity:**
- O(m×n), where m and n are the dimensions of the grid. Each cell is visited at most once.
> **Space complexity:**
- O(m×n), due to the recursive stack in DFS.
# Code
```javascript []
/**
 * @param {number[][]} grid
 * @return {number}
 */
var findMaxFish = function (grid) {
    const rows = grid.length;
    const cols = grid[0].length;
    let maxFish = 0;

    // Directions for adjacent cells: right, left, down, up
    const directions = [
        [0, 1], [0, -1], [1, 0], [-1, 0]
    ];

    // Helper function for DFS
    function dfs(r, c) {
        // Base case: if the cell is out of bounds or is land
        if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] === 0) {
            return 0;
        }

        // Collect the fish at the current cell
        let fish = grid[r][c];
        grid[r][c] = 0; // Mark the cell as visited

        // Explore all adjacent cells
        for (const [dr, dc] of directions) {
            fish += dfs(r + dr, c + dc);
        }

        return fish;
    }

    // Iterate over every cell in the grid
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            if (grid[r][c] > 0) { // Start DFS from every water cell
                maxFish = Math.max(maxFish, dfs(r, c));
            }
        }
    }

    return maxFish;
};
```

![DALL·E 2025-01-21 10.20.30 - A realistic, soft-toned image of a kind and humble person, sitting at a desk with a gentle smile, holding a sign that says_ 'Please upvote if this hel.webp](https://assets.leetcode.com/users/images/9853f524-994f-44ea-9704-97dff6a38509_1738035266.4657838.webp)

['JavaScript']