struct Solution {}
impl Solution {
    fn indices(grid: &[Vec<i32>]) -> impl Iterator<Item = (isize, isize)> + '_ {
        (0..grid.len()).flat_map(move |y| (0..grid[y].len()).map(move |x| (x as isize, y as isize)))
    }

    fn in_range(grid: &[Vec<i32>], y: isize, x: isize) -> bool {
        y >= 0 && y < grid.len() as isize && x >= 0 && x < grid[y as usize].len() as isize
    }

    fn count_empty(grid: &[Vec<i32>], y: isize, x: isize) -> i32 {
        [-1, 1]
            .into_iter()
            .flat_map(|d| [(x + d, y), (x, y + d)])
            .filter(|&(x, y)| !Self::in_range(grid, y, x) || grid[y as usize][x as usize] == 0)
            .count() as i32
    }

    pub fn island_perimeter(grid: Vec<Vec<i32>>) -> i32 {
        Self::indices(&grid)
            .filter(|&(x, y)| grid[y as usize][x as usize] != 0)
            .map(|(x, y)| Self::count_empty(&grid, y, x))
            .sum()
    }
}