1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-20 01:56:57 +02:00
LeetCode/rs/island-perimeter.rs
Matej Focko 3984bbb534
rs: add «463. Island Perimeter»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-04-18 23:53:09 +02:00

25 lines
915 B
Rust

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()
}
}