Files
contests/advent_of_code/2022/12/src/main.rs

94 lines
2.7 KiB
Rust

use std::collections::HashMap;
use pathfinding::prelude::dijkstra;
fn main() {
let test_input = include_str!("../input.txt")
.split_whitespace()
.collect::<Vec<&str>>();
let mut start = (0, 0);
let mut starts = Vec::new();
let mut end = (0, 0);
// let mut max_y = 0;
// let mut max_x = 0;
let mut points : HashMap<(i32, i32), i32> = HashMap::new();
let mut y = 0;
for line in test_input {
let mut x = 0;
for ch in line.chars() {
let mut c = ch;
if c == 'S' {
c = 'a';
start = (x, y);
}
if c == 'E' {
c = 'z';
end = (x, y);
}
if c == 'a' {
starts.push((x, y));
}
points.insert((x, y), c as i32 - 'a' as i32);
// max_x = x;
x += 1;
}
// max_y = y;
y += 1;
}
let r = dijkstra(
&start,
|&(x, y)| vec![((x-1, y), points.get(&(x-1, y)), (x, y)),
((x+1, y), points.get(&(x+1, y)), (x, y)),
((x, y+1), points.get(&(x, y+1)), (x, y)),
((x, y-1), points.get(&(x, y-1)), (x, y)),]
.into_iter()
.filter(|&(_, n, c)| match n {
None => false,
Some(&height) => height <= *points.get(&c).unwrap() + 1,
})
.map(|(coords, _, _)| (coords, 1)),
|&n| n == end);
println!("Number of steps taken: {}", r.expect("No path found").1);
let r = starts.into_iter().map(|s| dijkstra(
&s,
|&(x, y)| vec![((x-1, y), points.get(&(x-1, y)), (x, y)),
((x+1, y), points.get(&(x+1, y)), (x, y)),
((x, y+1), points.get(&(x, y+1)), (x, y)),
((x, y-1), points.get(&(x, y-1)), (x, y)),]
.into_iter()
.filter(|&(_, n, c)| match n {
None => false,
Some(&height) => height <= *points.get(&c).unwrap() + 1,
})
.map(|(coords, _, _)| (coords, 1)),
|&n| n == end))
.filter_map(|r| r)
.map(|(_, r)| r)
.min();
println!("Number of steps taken from any a: {}", r.expect("No paths found"));
// Testing the parsing
// for y in 0..=max_y {
// for x in 0..=max_x {
// if (x, y) == start {
// print!("S");
// } else if (x, y) == end {
// print!("E")
// } else {
// let c = from_u32((points.get(&(x, y)).unwrap() + 'a' as i32) as u32).unwrap();
// print!("{c}");
// }
// }
// println!();
// }
}