2658.cpp (1214B)
1 class Solution { 2 public: 3 int findMaxFish(vector<vector<int>> &grid) const { 4 static const int offset[] = {1, 0, -1, 0, 1}; 5 const int n = grid.size(), m = grid[0].size(); 6 const auto valid = [n, m](int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }; 7 int res = 0; 8 for (int i = 0; i < n; i++) { 9 for (int j = 0; j < m; j++) { 10 if (!grid[i][j]) continue; 11 int count = grid[i][j]; 12 grid[i][j] = 0; 13 14 queue<pair<int, int>> q; 15 q.push({i, j}); 16 while (!q.empty()) { 17 const auto [a, b] = q.front(); 18 for (int k = 0; k < 4; k++) { 19 const int x = a + offset[k]; 20 const int y = b + offset[k + 1]; 21 if (!valid(x, y)) continue; 22 if (!grid[x][y]) continue; 23 count += grid[x][y]; 24 grid[x][y] = 0; 25 q.push({x, y}); 26 } 27 q.pop(); 28 } 29 res = max(res, count); 30 } 31 } 32 return res; 33 } 34 };