Compare commits

..

2 Commits

Author SHA1 Message Date
36ceda33db Day 12, puzzle 2 2022-12-15 22:47:17 +01:00
3bdd5472aa Day 12, puzzle 1 2022-12-15 22:41:50 +01:00
4 changed files with 114 additions and 0 deletions

9
src/bin/d12p1.rs Normal file
View File

@ -0,0 +1,9 @@
use aoc22::{day12, util};
pub fn main() {
let heightmap = day12::parse_heightmap(&util::parse_input());
let dist = day12::path_steps(&heightmap, false).expect("No path found!?");
println!("Distance to target is {}", dist);
}

9
src/bin/d12p2.rs Normal file
View File

@ -0,0 +1,9 @@
use aoc22::{day12, util};
pub fn main() {
let heightmap = day12::parse_heightmap(&util::parse_input());
let dist = day12::path_steps(&heightmap, true).expect("No path found!?");
println!("Distance to target is {}", dist);
}

95
src/day12.rs Normal file
View File

@ -0,0 +1,95 @@
use std::collections::VecDeque;
use itertools::Itertools;
pub type Coord = (usize, usize);
#[derive(Debug)]
pub struct Heightmap {
pub map: Vec<Vec<usize>>,
pub rows: usize,
pub cols: usize,
pub start: Coord,
pub target: Coord,
}
pub fn parse_heightmap(input: &String) -> Heightmap {
let mut start = (usize::MAX, usize::MAX);
let mut target = (usize::MAX, usize::MAX);
let map = input
.lines()
.enumerate()
.map(|(row, l)| {
l.as_bytes()
.iter()
.enumerate()
.map(|(col, c)| {
if *c == ('S' as u8) {
start = (row, col);
0
} else if *c == ('E' as u8) {
target = (row, col);
25
} else {
(c - ('a' as u8)) as usize
}
})
.collect_vec()
})
.collect_vec();
assert_ne!(start.0, usize::MAX);
assert_ne!(target.0, usize::MAX);
let rows = map.len();
let cols;
if let itertools::MinMaxResult::MinMax(min, max) = map.iter().map(|r| r.len()).minmax() {
cols = min;
assert_eq!(min, max);
} else {
panic!("<2 rows?");
}
Heightmap {
map,
cols,
rows,
start,
target,
}
}
pub fn path_steps(map: &Heightmap, any_a: bool) -> Option<usize> {
let mut dist = vec![vec![usize::MAX; map.cols]; map.rows];
dist[map.target.0][map.target.1] = 0;
let mut next = VecDeque::new();
next.push_back(map.target);
let moves: Vec<(isize, isize)> = vec![(1, 0), (-1, 0), (0, 1), (0, -1)];
while let Some(coord) = next.pop_front() {
let curr_height = map.map[coord.0][coord.1];
let curr_dist = dist[coord.0][coord.1];
if curr_height == 0 && (any_a || coord == map.start) {
return Some(curr_dist);
}
for move_ in &moves {
let y = (coord.0 as isize) + move_.0;
if y < 0 || y >= map.rows as isize {
continue;
}
let x = (coord.1 as isize) + move_.1;
if x < 0 || x >= map.cols as isize {
continue;
}
let y = y as usize;
let x = x as usize;
if map.map[y][x] + 1 >= curr_height && dist[y][x] > curr_dist + 1 {
dist[y][x] = curr_dist + 1;
next.push_back((y, x));
}
}
}
None
}

View File

@ -1,6 +1,7 @@
pub mod day1; pub mod day1;
pub mod day10; pub mod day10;
pub mod day11; pub mod day11;
pub mod day12;
pub mod day2; pub mod day2;
pub mod day3; pub mod day3;
pub mod day4; pub mod day4;