}
pub fn score(map: &Map, start_positions: &[Position], multiple_paths: bool) -> u32 {
- fn neighbors((i, j): Position, ncols: usize, nrows: usize) -> Vec<Position> {
- let mut positions = Vec::new();
- if i > 0 {
- positions.push((i - 1, j));
- }
- if i < nrows - 1 {
- positions.push((i + 1, j));
- }
- if j > 0 {
- positions.push((i, j - 1));
- }
- if j < ncols - 1 {
- positions.push((i, j + 1));
- }
- positions
- }
-
fn get_nb_summits((i, j): Position, map: &Map, visited: &mut Option<DMatrix<bool>>) -> u32 {
if let Some(visited) = visited.as_mut() {
if visited[(i, j)] {
if map[(i, j)] == 9 {
1
} else {
- neighbors((i, j), map.ncols(), map.nrows())
- .into_iter()
- .map(|(i2, j2)| {
- if map[(i2, j2)] == map[(i, j)] + 1 {
- get_nb_summits((i2, j2), map, visited)
- } else {
- 0
- }
- })
- .sum()
+ [
+ (i.wrapping_sub(1), j),
+ (i + 1, j),
+ (i, j.wrapping_sub(1)),
+ (i, j + 1),
+ ]
+ .into_iter()
+ .map(|(i2, j2)| {
+ if i2 < map.nrows() && j2 < map.ncols() && map[(i2, j2)] == map[(i, j)] + 1 {
+ get_nb_summits((i2, j2), map, visited)
+ } else {
+ 0
+ }
+ })
+ .sum()
}
}