Leetcode 2658: Maximum Number of Fish in a Grid

grid47
grid47
Exploring patterns and algorithms
Feb 15, 2024 7 min read

You are given a 2D matrix grid of size m x n, where each cell can either be a land cell (represented by 0) or a water cell (represented by a positive integer indicating the number of fish present in that cell). A fisher can start at any water cell and perform two operations any number of times: catch all the fish in the current cell or move to an adjacent water cell. Your task is to determine the maximum number of fish the fisher can catch if they start at the optimal water cell.
Problem
Approach
Steps
Complexity
Input: You are given a 2D grid of integers, where 0 represents a land cell and a positive integer represents a water cell containing that many fish.
Example: Input: grid = [[0, 3, 2], [4, 0, 0], [1, 0, 3]]
Constraints:
• 1 <= m, n <= 10
• 0 <= grid[i][j] <= 10
Output: Return the maximum number of fish the fisher can catch by starting at the optimal water cell.
Example: Output: 9
Constraints:
• The output should be a single integer representing the maximum number of fish the fisher can catch.
Goal: The goal is to find the maximum number of fish that can be caught starting from any water cell, including moving through adjacent water cells.
Steps:
• Step 1: Iterate over each water cell in the grid.
• Step 2: For each water cell, perform a Depth-First Search (DFS) to count the total number of fish that can be caught starting from that cell and moving through adjacent water cells.
• Step 3: Track the maximum fish count found during the search.
Goal: The solution needs to respect the grid size constraints and ensure all operations are performed efficiently within these bounds.
Steps:
• Grid dimensions are at most 10x10, which allows for a depth-first search (DFS) to be performed within time limits.
Assumptions:
• The grid will contain at least one water cell.
Input: Input: grid = [[0, 3, 2], [4, 0, 0], [1, 0, 3]]
Explanation: Starting at cell (0, 1), the fisher can catch 3 fish. Then, they can move to (1, 0) and catch 4 more fish. A total of 9 fish can be caught.

Input: Input: grid = [[1, 0, 0], [0, 0, 0], [0, 0, 1]]
Explanation: The fisher can start at either (0, 0) or (2, 2) and catch 1 fish.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus