Easy & Detailed Approch 💡 | Simple BFS ✅ | All Languages 🔥 
IntuitionThe problem requires finding the maximum number of fish that can be collected from any connected group of cells in a grid. Each cell may contain some f
# Intuition
The problem requires finding the maximum number of fish that can be collected from any connected group of cells in a grid. Each cell may contain some fish, and we can move to adjacent cells (up, down, left, right) to collect fish from connected components. The intuition is to explore each connected component using a Breadth-First Search (BFS) or Depth-First Search (DFS) and calculate the total fish count in that component. The goal is to find the maximum fish count among all such components.

# Approach
1. **Initialization**:
   - Create a `vis` array of the same size as the grid to track visited cells.
   - Define directions for moving up, down, left, and right.

2. **BFS for Connected Components**:
   - For every cell in the grid:
     - If the cell contains fish (`grid[i][j] > 0`) and is not visited, start a BFS traversal from that cell.
     - Use a queue to explore all connected cells, marking them as visited.
     - Accumulate the total fish count for the connected component.

3. **Update Maximum Fish Count**:
   - After completing the BFS for a connected component, update the `maxi` variable to store the maximum fish count seen so far.

4. **Return Result**:
   - After traversing the entire grid, return the value of `maxi`.

# Complexity
- **Time Complexity**:  
  $$O(m \times n)$$  
  Each cell in the grid is visited once during the BFS traversal, where \(m\) is the number of rows and \(n\) is the number of columns.

- **Space Complexity**:  
  $$O(m \times n)$$  
  Space is used for the `vis` array and the BFS queue, both of which require space proportional to the number of cells in the grid.


# Code
```cpp []
class Solution {
public:
    int findMaxFish(vector<vector<int>>& grid) {
        int m = grid.size(); // Number of rows
        int n = grid[0].size(); // Number of columns

        vector<vector<int>> vis(m, vector<int>(n, 0)); // Visited array
        int row[4] = {-1, 0, 0, +1}; // Directions for rows
        int col[4] = {0, +1, -1, 0}; // Directions for columns
        int maxi = 0; // Maximum fish count in a connected component

        // Helper function to perform BFS and calculate the total fish in a component
        auto bfs = [&](int i, int j) {
            queue<pair<int, int>> q;
            q.push({i, j});
            vis[i][j] = 1; // Mark the starting cell as visited
            int sum = grid[i][j]; // Initialize the sum with the fish count of the starting cell

            while (!q.empty()) {
                auto [r, c] = q.front();
                q.pop();

                for (int k = 0; k < 4; k++) {
                    int nrow = r + row[k];
                    int ncol = c + col[k];

                    // Check if the new cell is valid, within bounds, unvisited, and has fish
                    if (nrow >= 0 && nrow < m && ncol >= 0 && ncol < n && !vis[nrow][ncol] && grid[nrow][ncol] > 0) {
                        vis[nrow][ncol] = 1; // Mark as visited
                        q.push({nrow, ncol}); // Add to the queue for further exploration
                        sum += grid[nrow][ncol]; // Add the fish count from the new cell
                    }
                }
            }
            return sum; // Return the total fish in the connected component
        };

        // Iterate through all cells in the grid
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // If the cell has fish and is not visited, start BFS from this cell
                if (grid[i][j] > 0 && !vis[i][j]) {
                    maxi = max(maxi, bfs(i, j)); // Update the maximum fish count
                }
            }
        }

        return maxi; // Return the maximum fish count from all connected components
    }
};


```
```javascript []
class Solution {
    findMaxFish(grid) {
        const m = grid.length; // Number of rows
        const n = grid[0].length; // Number of columns
        const vis = Array.from({ length: m }, () => Array(n).fill(0)); // Visited matrix
        const directions = [[-1, 0], [0, 1], [0, -1], [1, 0]]; // Directions (up, right, left, down)
        let maxi = 0; // Maximum fish count in any connected component

        // Helper function to perform BFS
        const bfs = (i, j) => {
            const queue = [[i, j]]; // Initialize the queue
            vis[i][j] = 1; // Mark the starting cell as visited
            let totalFish = grid[i][j]; // Initialize the fish count

            while (queue.length > 0) {
                const [r, c] = queue.shift(); // Dequeue the front cell

                // Explore all 4 possible directions
                for (const [dr, dc] of directions) {
                    const nr = r + dr; // Next row
                    const nc = c + dc; // Next column

                    // Check if the next cell is valid, unvisited, and has fish
                    if (nr >= 0 && nr < m && nc >= 0 && nc < n && vis[nr][nc] === 0 && grid[nr][nc] > 0) {
                        vis[nr][nc] = 1; // Mark the cell as visited
                        queue.push([nr, nc]); // Add the cell to the queue
                        totalFish += grid[nr][nc]; // Add the fish count to the total
                    }
                }
            }

            return totalFish; // Return the total fish count
        };

        // Iterate through all cells in the grid
        for (let i = 0; i < m; i++) {
            for (let j = 0; j < n; j++) {
                // If the cell contains fish and is unvisited, start a BFS
                if (grid[i][j] > 0 && vis[i][j] === 0) {
                    maxi = Math.max(maxi, bfs(i, j)); // Update the maximum fish count
                }
            }
        }

        return maxi; // Return the largest fish count
    }
}

```
```python []
from collections import deque

class Solution:
    def findMaxFish(self, grid):
        m, n = len(grid), len(grid[0])  # Dimensions of the grid
        vis = [[0] * n for _ in range(m)]  # Visited matrix
        directions = [(-1, 0), (0, 1), (0, -1), (1, 0)]  # Directions (up, right, left, down)
        maxi = 0  # To store the maximum fish count in any connected component

        # Helper function to perform BFS
        def bfs(i, j):
            q = deque()
            q.append((i, j))
            vis[i][j] = 1  # Mark the starting cell as visited
            total_fish = grid[i][j]  # Initialize the fish count from the starting cell

            while q:
                r, c = q.popleft()  # Get the current cell from the queue

                # Explore all 4 possible directions
                for dr, dc in directions:
                    nr, nc = r + dr, c + dc  # Compute the next cell's coordinates
                    # Check if the next cell is valid, unvisited, and contains fish
                    if 0 <= nr < m and 0 <= nc < n and not vis[nr][nc] and grid[nr][nc] > 0:
                        vis[nr][nc] = 1  # Mark the cell as visited
                        q.append((nr, nc))  # Add the cell to the queue
                        total_fish += grid[nr][nc]  # Add its fish count to the total

            return total_fish  # Return the total fish count in this component

        # Iterate through all cells in the grid
        for i in range(m):
            for j in range(n):
                # If the cell contains fish and is unvisited, start a BFS
                if grid[i][j] > 0 and not vis[i][j]:
                    maxi = max(maxi, bfs(i, j))  # Update the maximum fish count

        return maxi  # Return the largest fish count among all connected components

```
```java []
import java.util.*;

class Solution {
    public int findMaxFish(int[][] grid) {
        int m = grid.length; // Number of rows
        int n = grid[0].length; // Number of columns
        int[][] vis = new int[m][n]; // Visited array
        int[] row = {-1, 0, 0, 1}; // Directions for rows
        int[] col = {0, 1, -1, 0}; // Directions for columns
        int maxi = 0; // Maximum fish count in a connected component

        // BFS helper function
        int bfs(int i, int j) {
            Queue<int[]> q = new LinkedList<>();
            q.add(new int[] {i, j});
            vis[i][j] = 1; // Mark the starting cell as visited
            int sum = grid[i][j]; // Initialize the sum with the fish count

            while (!q.isEmpty()) {
                int[] curr = q.poll();
                int r = curr[0];
                int c = curr[1];

                for (int k = 0; k < 4; k++) {
                    int nr = r + row[k];
                    int nc = c + col[k];

                    // Check if the next cell is valid, unvisited, and has fish
                    if (nr >= 0 && nr < m && nc >= 0 && nc < n && vis[nr][nc] == 0 && grid[nr][nc] > 0) {
                        vis[nr][nc] = 1; // Mark the cell as visited
                        q.add(new int[] {nr, nc}); // Add the cell to the queue
                        sum += grid[nr][nc]; // Add the fish count to the sum
                    }
                }
            }

            return sum; // Return the total fish count
        }

        // Iterate through all cells in the grid
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // If the cell contains fish and is unvisited, start BFS
                if (grid[i][j] > 0 && vis[i][j] == 0) {
                    maxi = Math.max(maxi, bfs(i, j)); // Update the maximum fish count
                }
            }
        }

        return maxi; // Return the largest fish count
    }
}

```

![cat.jpg](https://assets.leetcode.com/users/images/51856b8c-d29e-4f79-95a2-d68de994fe11_1738030323.712718.jpeg)


['Depth-First Search', 'Breadth-First Search', 'Graph', 'Queue', 'Matrix', 'C++', 'Java', 'Python3']