impl Solution {
fn dfs(a : &mut Vec<Vec<i32>>, x : usize, y : usize) -> () { let (m, n) = (a.len(), a[0].len()); let (dx, dy) : ([i32; 4], [i32; 4]) = ([0, 0, 1, -1], [1, -1, 0, 0]); for i in 0..4 { let (xx, yy) : (i32, i32) = (x as i32 + dx[i], y as i32 + dy[i]); if xx >= m as i32 || xx < 0 || yy >= n as i32 || yy < 0 { continue; } let (nx, ny) = (xx as usize, yy as usize); if a[nx][ny] == 0 { continue; } a[nx][ny] = 0; Self::dfs(a, nx, ny); } }
pub fn num_enclaves(a: Vec<Vec<i32>>) -> i32 { let mut A = a; let (m, n, mut ans) = (A.len(), A[0].len(), 0); for i in 0..m { for j in 0..n { if i == 0 || j == 0 || i == m - 1 || j == n - 1 { if A[i][j] != 0 { A[i][j] = 0; Self::dfs(&mut A, i, j); } } } }
for i in 0..m { for j in 0..n { if A[i][j] != 0 { ans += 1; } } }
return ans; } }
|