Skip to content

Commit 2fb6164

Browse files
authored
Create 2658. Maximum Number of Fish in a Grid (#699)
2 parents 025b6ec + 1b54b7b commit 2fb6164

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
int bfs(vector<vector<int>>& grid, int r, int c) {
4+
int m = grid.size(), n = grid[0].size();
5+
queue<pair<int, int>> q;
6+
q.push({r, c});
7+
int totalFish = 0;
8+
int dr[] = {-1, 0, 0, 1};
9+
int dc[] = {0, -1, 1, 0};
10+
while (!q.empty()) {
11+
int row = q.front().first, col = q.front().second;
12+
q.pop();
13+
totalFish += grid[row][col];
14+
grid[row][col] = 0;
15+
for (int i = 0; i < 4; i++) {
16+
int nr = row + dr[i], nc = col + dc[i];
17+
if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] > 0) {
18+
q.push({nr, nc});
19+
}
20+
}
21+
}
22+
23+
return totalFish;
24+
}
25+
26+
int findMaxFish(vector<vector<int>>& grid) {
27+
int m = grid.size(), n = grid[0].size();
28+
int maxFish = 0;
29+
30+
for (int i = 0; i < m; i++) {
31+
for (int j = 0; j < n; j++) {
32+
if (grid[i][j] > 0) {
33+
maxFish = max(maxFish, bfs(grid, i, j));
34+
}
35+
}
36+
}
37+
38+
return maxFish;
39+
}
40+
};

0 commit comments

Comments
 (0)