From 746b5ad9a89776e69787f538db79cbbce6b333d7 Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Mon, 12 Dec 2022 18:27:52 +0100 Subject: [PATCH] Solve day12 part 2 --- 2022/day12_hill.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/2022/day12_hill.py b/2022/day12_hill.py index 48ddc73..55b15d8 100644 --- a/2022/day12_hill.py +++ b/2022/day12_hill.py @@ -1,6 +1,7 @@ from __future__ import annotations import dataclasses +import math import networkx as nx from networkx.algorithms.shortest_paths.generic import shortest_path @@ -43,6 +44,7 @@ class Hill: end: Cell width: int height: int + potential_starters: list[Cell] graph: nx.DiGraph = None def top(self, cell: Cell) -> Cell | None: @@ -97,6 +99,7 @@ def parse_data(data: list[str]) -> DataType: end_cell = None height = len(data) width = len(data[0]) + potential_starters = [] for y, row in enumerate(data): for x, char in enumerate(row): start, end = False, False @@ -113,7 +116,9 @@ def parse_data(data: list[str]) -> DataType: elif end: end_cell = cell cells.append(cell) - hill = Hill(cells, start_cell, end_cell, width, height) + if char == "a": + potential_starters.append(cell) + hill = Hill(cells, start_cell, end_cell, width, height, potential_starters) hill.build_graph() return hill @@ -124,9 +129,18 @@ def solve_part_1(data: DataType) -> int: def solve_part_2(data: DataType) -> int: - return 0 + min_length = math.inf + for candidate in data.potential_starters: + try: + path = shortest_path(data.graph, candidate, data.end) + path_length = len(path) + except nx.NetworkXNoPath: + path_length = math.inf + if path_length < min_length: + min_length = path_length + return min_length - 1 if __name__ == "__main__": - main("inputs/day12-test1", expected_part_1=31) - main("inputs/day12", expected_part_1=456) + main("inputs/day12-test1", expected_part_1=31, expected_part_2=29) + main("inputs/day12", expected_part_1=456, expected_part_2=454)