[LeetCode] Maximum Number of Fish in a Grid

2658. Maximum Number of Fish in a Grid

You are given a 0-indexed 2D matrix grid of size m x n, where (r, c) represents:

  • A land cell if grid[r][c] = 0, or
  • A water cell containing grid[r][c] fish, if grid[r][c] > 0.

A fisher can start at any water cell (r, c) and can do the following operations any number of times:

  • Catch all the fish at cell (r, c), or
  • Move to any adjacent water cell.

Return the maximum number of fish the fisher can catch if he chooses his starting cell optimally, or 0 if no water cell exists.

An adjacent cell of the cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) or (r - 1, c) if it exists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};

public:
int findMaxFish(vector<vector<int>>& A) {
int res = 0, n = A.size(), m = A[0].size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(A[i][j] == 0) continue;
int now = 0;
queue<pair<int, int>> q;
auto push = [&](int y, int x) {
if(0 <= y and y < n and 0 <= x and x < m and A[y][x]) {
now += A[y][x];
A[y][x] = 0;
q.push({y,x});
}
};
push(i,j);
while(q.size()) {
auto [y,x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
push(y + dy[i], x + dx[i]);
}
}
res = max(res, now);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/30/PS/LeetCode/maximum-number-of-fish-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.