add day 12, part 2

This commit is contained in:
Christian Ulrich 2022-12-13 03:39:56 +01:00
parent 0ffae23481
commit 623eeb882a
No known key found for this signature in database
GPG Key ID: 8241BE099775A097
2 changed files with 20 additions and 5 deletions

View File

@ -89,7 +89,7 @@ impl Map {
self.end_pos
}
fn neighbors(&self, pos: (usize, usize)) -> Option<Vec<(usize, usize)>> {
pub fn neighbors(&self, pos: (usize, usize)) -> Option<Vec<(usize, usize)>> {
let mut result = vec![];
let height = self.square_height(pos)?;
let (x, y) = pos;
@ -133,10 +133,13 @@ impl Map {
result
}
pub fn shortest_path(&self) -> ShortestPath {
pub fn shortest_path(&self, start_pos: Option<(usize, usize)>) -> ShortestPath {
// we reverse start_pos and end_pos so the ShortestPath will have the right order
let end_pos = match start_pos {
Some(pos) => pos,
None => self.start_pos,
};
let start_pos = self.end_pos;
let end_pos = self.start_pos;
let mut table = self.dijkstra_table(start_pos);
let mut unvisited: HashSet<(usize, usize)> = table.iter().map(|i| i.pos).collect();
@ -163,6 +166,18 @@ impl Map {
start_pos: start_pos,
}
}
pub fn lowest_positions(&self) -> Vec<(usize, usize)> {
let mut result = vec![];
for y in 0..self.squares.len() {
for x in 0..self.squares[0].len() {
if self.squares[y][x] as char == 'a' {
result.push((x, y));
}
}
}
result
}
}
impl Iterator for ShortestPath {
@ -178,7 +193,7 @@ impl Iterator for ShortestPath {
.iter()
.find(|i| i.pos == self.current)
.unwrap();
self.current = info.previous.unwrap();
self.current = info.previous?;
Some(result)
}
}

View File

@ -21,6 +21,6 @@ use common::Map;
fn main() -> Result<(), &'static str> {
let map = Map::from_stdin()?;
println!("{:?}", map.shortest_path().count());
println!("{:?}", map.shortest_path(None).count());
Ok(())
}