Maximum Number of Fish in a Grid

Yuqiu Ge
1 min readApr 30, 2023

https://leetcode.com/contest/biweekly-contest-103/problems/maximum-number-of-fish-in-a-grid/

  1. understand this first: https://yuqiuge.medium.com/number-of-islands-eb1a34a317ca
  2. add another step to these 6 steps: simplify the problem and build your process based on problems that you’ve already solved before
  3. get number of water in the grid
  4. count the fish in the water along the way
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (!visited[i][j] && grid[i][j] > 0) {
fishOfWaters.add(0);
dfs(grid, i, j);
numOfWaters++;
}
}
}

private void dfs(int[][] grid, int i, int j) {
if (i<0 || j<0 || i>=x || j >=y|| visited[i][j] || grid[i][j] == 0) return;
visited[i][j] = true;
if (grid[i][j] > 0) {
fishOfWaters.set(fishOfWaters.size()-1, fishOfWaters.get(fishOfWaters.size()-1) + grid[i][j]);
}
dfs(grid, i+1, j);
dfs(grid, i-1, j);
dfs(grid, i, j+1);
dfs(grid, i, j-1);
}

5. retrieve max fish

6. more info: https://github.com/geyuqiu/kata-bootstraps/blob/develop/java/junit5/src/main/java/leetcode/FindMaxFish.java

--

--