LeetCode 1254. Number of Closed Islands

Problem Statement

Typical BFS.


use std::collections::VecDeque;

impl Solution {
pub fn closed_island(grid: Vec<Vec<i32>>) -> i32 {
let (m, n, mut ans) = (grid.len(), grid[0].len(), 0);
let (dx, dy) : ([i32; 4], [i32; 4]) = ([1, -1, 0, 0], [0, 0, 1, -1]);
let mut g = grid;
for i in 0..m {
for j in 0..n {
if g[i][j] == 1 || g[i][j] == -1 {
continue;
}
let mut q = VecDeque::new();
q.push_back((i, j));
g[i][j] = -1;
let mut valid = true;

while !q.is_empty() {
let (x, y) = q.pop_front().unwrap();
for k in 0..4 {
let (xx, yy) = (x as i32 + dx[k], y as i32 + dy[k]);
if xx < 0 || yy < 0 || xx >= m as i32 || yy >= n as i32 {
valid = false; continue;
}
let (nx, ny) = (xx as usize, yy as usize);
if g[nx][ny] == 1 || g[nx][ny] == -1 {
continue;
}
q.push_back((nx, ny));
g[nx][ny] = -1;
}
}

if valid {
ans += 1;
}
}
}

return ans;
}
}