Day 12, puzzle 2
This commit is contained in:
parent
3bdd5472aa
commit
36ceda33db
|
@ -3,7 +3,7 @@ use aoc22::{day12, util};
|
|||
pub fn main() {
|
||||
let heightmap = day12::parse_heightmap(&util::parse_input());
|
||||
|
||||
let dist = day12::path_steps(&heightmap).expect("No path found!?");
|
||||
let dist = day12::path_steps(&heightmap, false).expect("No path found!?");
|
||||
|
||||
println!("Distance to target is {}", dist);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
22
src/day12.rs
22
src/day12.rs
|
@ -59,19 +59,20 @@ pub fn parse_heightmap(input: &String) -> Heightmap {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn path_steps(map: &Heightmap) -> Option<usize> {
|
||||
pub fn path_steps(map: &Heightmap, any_a: bool) -> Option<usize> {
|
||||
let mut dist = vec![vec![usize::MAX; map.cols]; map.rows];
|
||||
dist[map.start.0][map.start.1] = 0;
|
||||
dist[map.target.0][map.target.1] = 0;
|
||||
let mut next = VecDeque::new();
|
||||
next.push_back(map.start);
|
||||
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() {
|
||||
if coord == map.target {
|
||||
break;
|
||||
}
|
||||
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 {
|
||||
|
@ -83,17 +84,12 @@ pub fn path_steps(map: &Heightmap) -> Option<usize> {
|
|||
}
|
||||
let y = y as usize;
|
||||
let x = x as usize;
|
||||
if map.map[y][x] <= curr_height + 1 && dist[y][x] > curr_dist + 1 {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let d = dist[map.target.0][map.target.1];
|
||||
if d < usize::MAX {
|
||||
Some(d)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
None
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue