diff --git a/AoC_2025/Day07.cs b/AoC_2025/Day07.cs index 55d63d3..7b99658 100644 --- a/AoC_2025/Day07.cs +++ b/AoC_2025/Day07.cs @@ -29,14 +29,14 @@ public class Day07 : IPuzzleSolver { var grid = ParsePuzzleInput(pathToPuzzleInput); var start = GetStart(grid); - var nodesWithCount = GetNodesTraversedWitTimelineCount(grid, start, [], []); - return nodesWithCount[start]; + var nodesWithCount = GetTimelinesCountRecursive(grid, start, []); + return nodesWithCount; } public long SolvePart2Again(string pathToPuzzleInput) { var grid = ParsePuzzleInput(pathToPuzzleInput); - var nodesWithCount = GetNodesTraversedWitTimelineCount(grid); + var nodesWithCount = GetTimelinesCount(grid); return nodesWithCount.Sum(); } @@ -76,40 +76,29 @@ public class Day07 : IPuzzleSolver } } - private Dictionary GetNodesTraversedWitTimelineCount(string[] grid, Coordinate current, HashSet path, Dictionary nodeCountVisited) + // Dictionary only for memoization + private long GetTimelinesCountRecursive(string[] grid, Coordinate current, Dictionary nodeCountVisited) { - if (current.x >= grid.Length || nodeCountVisited.ContainsKey(current)) + if (current.x >= grid.Length) { - nodeCountVisited = UpdateNodeVisitedCounts(current, path, nodeCountVisited); - return nodeCountVisited; + return 1; } - - nodeCountVisited[current] = 0; - path.Add(current); + if(nodeCountVisited.TryGetValue(current, out var count)) return count; if (grid[current.x][current.y] == '^') { - var resLeft = GetNodesTraversedWitTimelineCount(grid, (current.x, current.y - 1), [..path], nodeCountVisited); - var resRight = GetNodesTraversedWitTimelineCount(grid, (current.x, current.y + 1), [..path], resLeft); - return resRight; + var resLeft = GetTimelinesCountRecursive(grid, (current.x, current.y - 1), nodeCountVisited); + var resRight = GetTimelinesCountRecursive(grid, (current.x, current.y + 1), nodeCountVisited); + nodeCountVisited[current] = resLeft + resRight; + return resLeft + resRight; } - - var res = GetNodesTraversedWitTimelineCount(grid, (current.x + 1, current.y), [..path], nodeCountVisited); + + var res = GetTimelinesCountRecursive(grid, (current.x + 1, current.y), nodeCountVisited); + nodeCountVisited[current] = res; return res; } - private static Dictionary UpdateNodeVisitedCounts(Coordinate current, HashSet path, Dictionary nodeCountVisited) - { - var addAmount = nodeCountVisited.GetValueOrDefault(current, 1); - foreach (var node in path) - { - nodeCountVisited[node] += addAmount; - } - - return nodeCountVisited; - } - - private long[] GetNodesTraversedWitTimelineCount(string[] grid) + private long[] GetTimelinesCount(string[] grid) { var numbersGrid = grid .Select(line => line.Select(c => 0L).ToArray())