#2658
Medium Algorithms Maximum number of fish in a grid
Array Depth-First Search Breadth-First Search Union-Find Matrix
70.5% acceptance
Feb 25, 2026
951
67
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 do the following operations:
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.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn find_max_fish(grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
let mut visited = vec![vec![false; n]; m];
let mut max_fish = 0;
for r in 0..m {
for c in 0..n {
if grid[r][c] > 0 && !visited[r][c] {
// BFS flood fill
let mut total = 0;
let mut queue = std::collections::VecDeque::new();
queue.push_back((r, c));
visited[r][c] = true;
while let Some((row, col)) = queue.pop_front() {
total += grid[row][col];
for (dr, dc) in [(-1i32, 0), (1, 0), (0, -1i32), (0, 1)] {
let nr = row as i32 + dr;
let nc = col as i32 + dc;
if nr >= 0 && nr < m as i32 && nc >= 0 && nc < n as i32 {
let (nr, nc) = (nr as usize, nc as usize);
if grid[nr][nc] > 0 && !visited[nr][nc] {
visited[nr][nc] = true;
queue.push_back((nr, nc));
}
}
}
}
if total > max_fish { max_fish = total; }
}
}
}
max_fish
}
}