#1020
Medium Algorithms Number of enclaves
Array Depth-First Search Breadth-First Search Union-Find Matrix
71.5% acceptance
Feb 25, 2026
4592
89
You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.
A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.
Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn num_enclaves(mut grid: Vec<Vec<i32>>) -> i32 {
let (m, n) = (grid.len(), grid[0].len());
fn dfs(g: &mut Vec<Vec<i32>>, r: usize, c: usize) {
if r >= g.len() || c >= g[0].len() || g[r][c] != 1 { return; }
g[r][c] = 0;
if r > 0 { dfs(g, r-1, c); }
dfs(g, r+1, c); dfs(g, r, c+1);
if c > 0 { dfs(g, r, c-1); }
}
for r in 0..m { dfs(&mut grid, r, 0); dfs(&mut grid, r, n-1); }
for c in 0..n { dfs(&mut grid, 0, c); dfs(&mut grid, m-1, c); }
grid.iter().flatten().sum()
}
}