From 6974ee5dff290ebd7c39300668e940e6cb91de1f Mon Sep 17 00:00:00 2001 From: Joscha Date: Mon, 12 Dec 2022 11:43:45 +0100 Subject: [PATCH] [rs] Solve 2022_12 part 2 --- inputs/2022/2022_12.solution | 2 +- rs/src/y2022/d12.rs | 22 ++++++++++++++++++++-- sample_inputs/2022/2022_12.solution | 2 +- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/inputs/2022/2022_12.solution b/inputs/2022/2022_12.solution index 11cc47d..6f69e5e 100644 --- a/inputs/2022/2022_12.solution +++ b/inputs/2022/2022_12.solution @@ -1,2 +1,2 @@ Part 1: 383 -Part 2: ??? +Part 2: 377 diff --git a/rs/src/y2022/d12.rs b/rs/src/y2022/d12.rs index faf0add..9301f08 100644 --- a/rs/src/y2022/d12.rs +++ b/rs/src/y2022/d12.rs @@ -150,8 +150,12 @@ fn path_length(steps: &Grid, start: (i32, i32), end: (i32, i32)) -> usize let mut pos = end; let mut length = 0; while pos != start { - pos = steps.ati(pos.0, pos.1).unwrap().prev; - length += 1; + if let Some(step) = steps.ati(pos.0, pos.1) { + pos = step.prev; + length += 1; + } else { + return usize::MAX; + } } length } @@ -185,4 +189,18 @@ pub fn solve(input: String) { let steps = dijkstra(&grid, starti, endi); let part1 = path_length(&steps, starti, endi); println!("Part 1: {part1}"); + + let mut part2 = usize::MAX; + for y in 0..grid.height { + for x in 0..grid.width { + if *grid.at(x, y).unwrap() == 0 { + let starti = (x as i32, y as i32); + let endi = (end.0 as i32, end.1 as i32); + let steps = dijkstra(&grid, starti, endi); + let length = path_length(&steps, starti, endi); + part2 = part2.min(length); + } + } + } + println!("Part 2: {part2}"); } diff --git a/sample_inputs/2022/2022_12.solution b/sample_inputs/2022/2022_12.solution index a6f74f1..b540e11 100644 --- a/sample_inputs/2022/2022_12.solution +++ b/sample_inputs/2022/2022_12.solution @@ -1,2 +1,2 @@ Part 1: 31 -Part 2: ??? +Part 2: 29