From 4ac60dcd80301dd2553b4ab32251b640c34effbd Mon Sep 17 00:00:00 2001 From: pareronia <49491686+pareronia@users.noreply.github.com> Date: Sat, 23 Dec 2023 20:10:06 +0100 Subject: [PATCH] AoC 2023 Day 23 - java - faster --- src/main/java/AoC2023_23.java | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/main/java/AoC2023_23.java b/src/main/java/AoC2023_23.java index 1ee9c163..64b519e6 100644 --- a/src/main/java/AoC2023_23.java +++ b/src/main/java/AoC2023_23.java @@ -4,6 +4,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import com.github.pareronia.aoc.CharGrid; @@ -75,7 +76,18 @@ public int findLongestHikeLength() { log(pois); final Map> graph = this.buildGraph(pois, false); log(graph); - return this.findLongest(graph, start, end, new HashSet<>()); + final int distFromStart = graph.get(this.start).iterator().next().weight; + final int distToEnd = graph.get(this.end).iterator().next().weight; + final Cell newStart = graph.entrySet().stream() + .filter(e -> e.getValue().contains(new Edge(this.start, distFromStart))) + .map(Entry::getKey) + .findFirst().orElseThrow(); + final Cell newEnd = graph.entrySet().stream() + .filter(e -> e.getValue().contains(new Edge(this.end, distToEnd))) + .map(Entry::getKey) + .findFirst().orElseThrow(); + return distFromStart + distToEnd + + this.findLongest(graph, newStart, newEnd, new HashSet<>()); } public int findLongestHikeLengthWithDownwardSlopesOnly() { @@ -83,7 +95,7 @@ public int findLongestHikeLengthWithDownwardSlopesOnly() { log(pois); final Map> graph = this.buildGraph(pois, true); log(graph); - return this.findLongest(graph, start, end, new HashSet<>()); + return this.findLongest(graph, this.start, this.end, new HashSet<>()); } private int findLongest(