|
| 1 | +package main |
| 2 | + |
| 3 | +import "strings" |
| 4 | + |
| 5 | +func doPartTwo(input string) int { |
| 6 | + lines := strings.Split(strings.TrimSpace(input), "\n") |
| 7 | + |
| 8 | + // Build the adjacency list graph |
| 9 | + devices := make(map[string][]string) |
| 10 | + for _, line := range lines { |
| 11 | + s := strings.Fields(line) |
| 12 | + device := strings.TrimSuffix(s[0], ":") |
| 13 | + devices[device] = s[1:] |
| 14 | + } |
| 15 | + |
| 16 | + // Count paths from "svr" to "out" that visit both "dac" and "fft" |
| 17 | + memo := make(map[string]int) |
| 18 | + pathCount := countPathsWithRequiredMemo(devices, "svr", "out", []string{"dac", "fft"}, make(map[string]bool), make(map[string]bool), memo) |
| 19 | + |
| 20 | + return pathCount |
| 21 | +} |
| 22 | + |
| 23 | +// countPathsWithRequiredMemo counts paths with memoization |
| 24 | +func countPathsWithRequiredMemo(graph map[string][]string, current, target string, required []string, visited map[string]bool, foundRequired map[string]bool, memo map[string]int) int { |
| 25 | + // If we reached the target |
| 26 | + if current == target { |
| 27 | + // Check if all required nodes were visited |
| 28 | + for _, req := range required { |
| 29 | + if !foundRequired[req] { |
| 30 | + return 0 |
| 31 | + } |
| 32 | + } |
| 33 | + return 1 |
| 34 | + } |
| 35 | + |
| 36 | + // Create memo key from current node and which required nodes have been found |
| 37 | + memoKey := current |
| 38 | + for _, req := range required { |
| 39 | + if foundRequired[req] { |
| 40 | + memoKey += "+" + req |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // Check memo |
| 45 | + if val, exists := memo[memoKey]; exists { |
| 46 | + return val |
| 47 | + } |
| 48 | + |
| 49 | + // Mark current node as visited |
| 50 | + visited[current] = true |
| 51 | + defer func() { visited[current] = false }() |
| 52 | + |
| 53 | + // Check if current node is a required node |
| 54 | + wasFound := make(map[string]bool) |
| 55 | + for _, req := range required { |
| 56 | + if current == req && !foundRequired[req] { |
| 57 | + foundRequired[req] = true |
| 58 | + wasFound[req] = true |
| 59 | + } |
| 60 | + } |
| 61 | + defer func() { |
| 62 | + for req := range wasFound { |
| 63 | + foundRequired[req] = false |
| 64 | + } |
| 65 | + }() |
| 66 | + |
| 67 | + totalPaths := 0 |
| 68 | + |
| 69 | + // Explore all neighbors |
| 70 | + for _, neighbor := range graph[current] { |
| 71 | + if visited[neighbor] { |
| 72 | + continue |
| 73 | + } |
| 74 | + |
| 75 | + totalPaths += countPathsWithRequiredMemo(graph, neighbor, target, required, visited, foundRequired, memo) |
| 76 | + } |
| 77 | + |
| 78 | + memo[memoKey] = totalPaths |
| 79 | + return totalPaths |
| 80 | +} |
0 commit comments