Leetcode Problem 2658. Maximum Number of Fish in a Grid

2658. Maximum Number of Fish in a Grid

Leetcode Solutions

Depth-First Search (DFS) to Find Maximum Fish

  1. Initialize a variable maxFish to store the maximum number of fish caught.
  2. Iterate through each cell in the grid.
  3. If the current cell is a water cell (contains fish), perform a DFS from this cell.
  4. In the DFS function: a. Check if the current cell is out of bounds or is a land cell (no fish), return 0. b. Save the number of fish in the current cell to a variable fishCount. c. Set the current cell to 0 (mark as visited) to avoid revisiting. d. Recursively call DFS for all adjacent cells (up, down, left, right) and add their fish counts to fishCount. e. Return fishCount.
  5. Update maxFish with the maximum of its current value and the fish count returned by DFS.
  6. After iterating through all cells, return maxFish as the result.
UML Thumbnail

Breadth-First Search (BFS) to Find Maximum Fish

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...