struct Solution {} impl Solution { fn indices(grid: &[Vec]) -> impl Iterator + '_ { (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], 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], 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>) -> 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() } }