diff --git a/AdventOfCode/Day21.cs b/AdventOfCode/Day21.cs index d6fd0f6..254a14b 100644 --- a/AdventOfCode/Day21.cs +++ b/AdventOfCode/Day21.cs @@ -41,10 +41,12 @@ private int GetShortestPath(string code) two.AddRange(GetAllPaths(path, _directionalPad, cache)); } + var lengthCache = cache.ToDictionary(x => x.Key, y => y.Value.Min(s => s.Length)); + int shortest = int.MaxValue; foreach (string path in two) { - var t = GetPathLength(path, _directionalPad, cache); + var t = GetPathLength(path, _directionalPad, lengthCache); if (t < shortest) { shortest = t; @@ -74,7 +76,7 @@ private List GetAllPaths( } else { - segments = GetAllPaths(from, to, "", cache); + segments = GetAllPaths(from, to, ""); cache[(from, to)] = segments; } @@ -90,7 +92,7 @@ private List GetAllPaths( private int GetPathLength( string code, Dictionary pad, - Dictionary<(Position, Position), List> cache + Dictionary<(Position, Position), int> lengthCache ) { Position from = pad['A']; @@ -100,17 +102,17 @@ private int GetPathLength( { Position to = pad[button]; - if (cache.ContainsKey((from, to))) + if (lengthCache.ContainsKey((from, to))) { - length += cache[(from, to)][0].Length; - length++; + length += lengthCache[(from, to)]; + length++; // A } else { - var segments = GetAllPaths(from, to, "", cache); - cache[(from, to)] = segments; - length += cache[(from, to)][0].Length; - length++; + var segments = GetAllPaths(from, to, ""); + lengthCache[(from, to)] = segments.Min(s => s.Length); + length += lengthCache[(from, to)]; + length++; // A } from = to; @@ -122,8 +124,7 @@ private int GetPathLength( private List GetAllPaths( Position from, Position to, - string currentPath, - Dictionary<(Position, Position), List> cache + string currentPath ) { List paths = new List(); @@ -135,19 +136,19 @@ private List GetAllPaths( if (from.I - to.I > 0) { - paths.AddRange(GetAllPaths(new Position(from.I - 1, from.J), to, currentPath + "^", cache)); + paths.AddRange(GetAllPaths(new Position(from.I - 1, from.J), to, currentPath + "^")); } if (from.I - to.I < 0) { - paths.AddRange(GetAllPaths(new Position(from.I + 1, from.J), to, currentPath + "V", cache)); + paths.AddRange(GetAllPaths(new Position(from.I + 1, from.J), to, currentPath + "V")); } if (from.J - to.J > 0) { - paths.AddRange(GetAllPaths(new Position(from.I, from.J - 1), to, currentPath + "<", cache)); + paths.AddRange(GetAllPaths(new Position(from.I, from.J - 1), to, currentPath + "<")); } if (from.J - to.J < 0) { - paths.AddRange(GetAllPaths(new Position(from.I, from.J + 1), to, currentPath + ">", cache)); + paths.AddRange(GetAllPaths(new Position(from.I, from.J + 1), to, currentPath + ">")); } return paths;