-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
94 lines (80 loc) 路 2.08 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#![allow(non_snake_case)]
use {
aoc::{
graph::BFS,
grid::{Cell, CharGrid, Grid},
Puzzle,
},
std::collections::HashSet,
};
const START: char = 'S';
const END: char = 'E';
const MIN: char = 'a';
const MAX: char = 'z';
struct HeightMap {
grid: CharGrid,
start: Cell,
}
struct AoC2022_12;
impl AoC2022_12 {
fn solve(&self, map: &HeightMap, end_points: &HashSet<char>) -> usize {
let is_end = |cell| end_points.contains(&map.grid.get(&cell));
let get_value = |cell| match map.grid.get(&cell) {
START => MIN as i8,
END => MAX as i8,
ch => ch as i8,
};
let adjacent = |cell| {
map.grid
.capital_neighbours(&cell)
.iter()
.filter(|&n| get_value(cell) - get_value(*n) <= 1)
.cloned()
.collect::<Vec<Cell>>()
};
BFS::execute(map.start, is_end, adjacent)
}
}
impl aoc::Puzzle for AoC2022_12 {
type Input = HeightMap;
type Output1 = usize;
type Output2 = usize;
aoc::puzzle_year_day!(2022, 12);
fn parse_input(&self, lines: Vec<String>) -> HeightMap {
let grid = CharGrid::from(
&lines.iter().map(AsRef::as_ref).collect::<Vec<_>>(),
);
let start = grid.find_first_matching(|val| val == END).unwrap();
HeightMap { grid, start }
}
fn part_1(&self, map: &HeightMap) -> usize {
self.solve(map, &HashSet::from([START]))
}
fn part_2(&self, map: &HeightMap) -> usize {
self.solve(map, &HashSet::from([START, MIN]))
}
fn samples(&self) {
#[rustfmt::skip]
let test =
"Sabqponm\n\
abcryxxl\n\
accszExk\n\
acctuvwj\n\
abdefghi";
aoc::puzzle_samples! {
self, part_1, test, 31,
self, part_2, test, 29
};
}
}
fn main() {
AoC2022_12 {}.run(std::env::args());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn samples() {
AoC2022_12 {}.samples();
}
}