From cfe67b7889885977e5b978b10ebf9738c8dbc236 Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Wed, 14 Dec 2022 19:35:58 +0100 Subject: [PATCH] day12 - improved --- day12.py | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/day12.py b/day12.py index a8dbc88..25b5527 100644 --- a/day12.py +++ b/day12.py @@ -1,3 +1,4 @@ +from collections import deque from heapq import heappush, heappop from tools.aoc import AOCDay from tools.coordinate import Coordinate, DistanceAlgorithm @@ -47,6 +48,32 @@ def get_dijkstra_path(height_map: Grid, start: Coordinate, end: Coordinate) -> i return steps +def get_bfs_path(height_map: Grid, end: Coordinate) -> int: + v = {end: None} + q = deque() + q.append(end) + while q: + cur = q.popleft() + cur_v = height_map.get(cur) + if cur_v == 0: + end = cur + break + + for c in height_map.getNeighboursOf(cur, includeDiagonal=False): + if c in v or height_map.get(c) + 1 < cur_v: + continue + + v[c] = cur + q.append(c) + + steps = 0 + while end in v: + steps += 1 + end = v[end] + + return steps + + class Day(AOCDay): inputs = [ [ @@ -84,15 +111,8 @@ class Day(AOCDay): return get_dijkstra_path(*self.get_map()) def part2(self) -> Any: - min_steps = float("inf") - height_map, start, end = self.get_map() - for c in height_map.getActiveCells(): - if height_map.get(c) == 0: - steps_from_here = get_dijkstra_path(height_map, c, end) - if steps_from_here is not None and steps_from_here + 1 < min_steps: - min_steps = steps_from_here + 1 - - return min_steps - 1 + height_map, _, end = self.get_map() + return get_bfs_path(height_map, end) - 1 if __name__ == '__main__':