Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
3
Indexable
Never
from typing import List

class Solution:
    def findMaxFish(self, grid: List[List[int]]) -> int:
        from collections import deque

        m, n = len(grid), len(grid[0])

        # Function to get valid adjacent water cells
        def get_adjacent_water_cells(r, c):
            for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                nr, nc = r + dr, c + dc
                if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] > 0:
                    yield nr, nc

        # BFS to find the maximum fish that can be caught starting from (r, c)
        def bfs(r, c):
            visited = set()
            queue = deque([(r, c)])
            total_fish = 0

            while queue:
                r, c = queue.popleft()
                if (r, c) not in visited:
                    visited.add((r, c))
                    total_fish += grid[r][c]
                    for nr, nc in get_adjacent_water_cells(r, c):
                        if (nr, nc) not in visited:
                            queue.append((nr, nc))
            
            return total_fish

        max_fish_catch = 0
        for r in range(m):
            for c in range(n):
                if grid[r][c] > 0:
                    max_fish_catch = max(max_fish_catch, bfs(r, c))

        return max_fish_catch
Leave a Comment