Refactor 2026 Day06 middle node detection to use reeated edge removal instead of BFS

This commit is contained in:
Sebastian Lindemeier committed 2026-12-06 17:10:21 +01:00
1 parent f66a188a0e
commit bfbd68bd83
1 file changed
+31 -24
+31 -24
View File
@@ -43,10 +43,9 @@ public class Day06 : IPuzzleSolver<string>
public string SolvePart1(string pathToPuzzleInput)
{
var gridInstructions = ParsePuzzleInput(pathToPuzzleInput);
var possibleMiddles = gridInstructions.Where(conn => conn.Value.Count == 4);
var middle = possibleMiddles.MinBy(m => GetMaxDistanceFromEdge(m.Key, gridInstructions));
return middle.Key;
var grid = ParsePuzzleInput(pathToPuzzleInput);
var middle = GetMiddleNode(grid);
return middle;
}
public string SolvePart2Test(string pathToPuzzleInput)
@@ -67,6 +66,34 @@ public class Day06 : IPuzzleSolver<string>
return $"{location.x},{location.y}";
}
private static string GetMiddleNode(Dictionary<string, HashSet<string>> grid)
{
while (grid.Keys.Count > 1)
{
var edges = GetEdges(grid);
foreach (var edge in edges)
{
grid.Remove(edge);
}
foreach (var (_, connections) in grid)
{
connections.ExceptWith(edges);
}
}
return grid.First().Key;
}
private static string[] GetEdges(Dictionary<string, HashSet<string>> grid)
{
var edges = grid
.Where(conn => conn.Value.Count < 4)
.Select(conn => conn.Key)
.ToArray();
return edges;
}
private static (int x, int y) DetermineLocation(string key, List<(string key, (int x, int y))> satellites, Dictionary<string, HashSet<string>> gridInstructions)
{
var intersections = GetPossibleLocations(key, satellites, gridInstructions);
@@ -130,24 +157,4 @@ public class Day06 : IPuzzleSolver<string>
yield return (x1 + x2, y1 - y2);
}
}
private static int GetMaxDistanceFromEdge(string from, Dictionary<string, HashSet<string>> gridInstrucions)
{
var maxDistance = 0;
var queue = new Queue<(string, int)>();
var seen = new HashSet<string>();
queue.Enqueue((from, 0));
while (queue.Count > 0)
{
var (current, distance) = queue.Dequeue();
if(!seen.Add(current))
continue;
maxDistance = Math.Max(maxDistance, distance);
foreach (var next in gridInstrucions[current])
{
queue.Enqueue((next, distance + 1));
}
}
return maxDistance;
}
}