1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

rs: add «463. Island Perimeter»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-04-18 23:53:09 +02:00
parent e53159dd8d
commit 3984bbb534
Signed by: mfocko
GPG key ID: 7C47D46246790496

25
rs/island-perimeter.rs Normal file
View file

@ -0,0 +1,25 @@
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()
}
}