forked from fspoettel/advent-of-code-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
12.rs
70 lines (59 loc) · 1.68 KB
/
12.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
use advent_of_code::{shortest_path::shortest_path, Point, SimpleGrid};
type Input<'a> = (SimpleGrid<char>, Point, Point);
fn parse(input: &str) -> Input {
let mut start: Option<Point> = None;
let mut end: Option<Point> = None;
let grid: SimpleGrid<char> = SimpleGrid::from_str(input, &mut |c, x, y| match c {
'S' => {
start = Some(Point {
x: x as isize,
y: y as isize,
});
'a'
}
'E' => {
end = Some(Point {
x: x as isize,
y: y as isize,
});
'z'
}
c => c,
});
(grid, start.unwrap(), end.unwrap())
}
fn find_path(grid: &SimpleGrid<char>, start: Vec<Point>, end: Point) -> Option<usize> {
shortest_path(
grid,
&start,
&end,
|_| 1,
|a, b| (*grid.get(b) as isize - *grid.get(a) as isize) < 2,
)
}
pub fn part_one((grid, start, end): Input) -> Option<usize> {
find_path(&grid, vec![start], end)
}
pub fn part_two((grid, _, end): Input) -> Option<usize> {
let start_points: Vec<Point> = grid
.points()
.into_iter()
.filter(|point| *grid.get(point) == 'a')
.collect();
find_path(&grid, start_points, end)
}
advent_of_code::main!(12);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(parse(&advent_of_code::template::read_file("examples", 12)));
assert_eq!(result, Some(31));
}
#[test]
fn test_part_two() {
let result = part_two(parse(&advent_of_code::template::read_file("examples", 12)));
assert_eq!(result, Some(29));
}
}