96 lines
2.1 KiB
Python
96 lines
2.1 KiB
Python
#!/usr/bin/env python
|
|
|
|
# https://adventofcode.com/2025/day/11
|
|
|
|
f = open("day11input.txt", "r")
|
|
#f = open("testinput.txt", "r")
|
|
|
|
graph = {}
|
|
for line in f.readlines():
|
|
node, outputs = line.strip("\n").split(":")
|
|
graph[node] = outputs.strip().split(" ")
|
|
|
|
|
|
def part1(current_path: list[str] | str, end: str) -> None:
|
|
if isinstance(current_path, str):
|
|
current_path = [current_path]
|
|
|
|
node = current_path[-1]
|
|
|
|
# check for dead ends
|
|
if node not in graph.keys():
|
|
return
|
|
|
|
# check if end node is reachable from current node
|
|
if end in graph[node]:
|
|
found_paths.append(current_path + [end])
|
|
return
|
|
|
|
# check all outputs
|
|
for output in graph[node]:
|
|
# avoid loops
|
|
if output in current_path:
|
|
continue
|
|
part1(current_path + [output], end)
|
|
|
|
|
|
|
|
def part2(start: str, end: str) -> int:
|
|
print(f"STARTING BACKWARDS SEARCH FROM {end} TO {start}")
|
|
num_paths = {end: 0}
|
|
|
|
def backsearch(target_node: str, current_node: str) -> int:
|
|
# init num_paths value for current node
|
|
num_paths[current_node] = 0
|
|
|
|
# find nodes with edges into current node
|
|
inputs = list(filter(lambda n: current_node in graph[n], graph.keys()))
|
|
|
|
# check if current_node is a dead end
|
|
if len(inputs) == 0:
|
|
return
|
|
|
|
# loop over input nodes
|
|
for node in inputs:
|
|
# check if node is the target node
|
|
if node == target_node:
|
|
num_paths[current_node] = 1
|
|
|
|
# input node was visited already
|
|
elif node in num_paths.keys():
|
|
num_paths[current_node] += num_paths[node]
|
|
|
|
# input node was not yet visited
|
|
else:
|
|
backsearch(target_node, node)
|
|
num_paths[current_node] += num_paths[node]
|
|
|
|
return
|
|
|
|
backsearch(start, end)
|
|
return num_paths[end]
|
|
|
|
|
|
|
|
|
|
# part 1
|
|
found_paths = []
|
|
part1("you", "out")
|
|
print(len(found_paths))
|
|
|
|
# part2
|
|
svr2dac = part2("svr", "dac")
|
|
print(svr2dac)
|
|
dac2fft = part2("dac", "fft")
|
|
print(dac2fft)
|
|
fft2out = part2("fft", "out")
|
|
print(fft2out)
|
|
svr2fft = part2("svr", "fft")
|
|
print(svr2fft)
|
|
fft2dac = part2("fft", "dac")
|
|
print(fft2dac)
|
|
dac2out = part2("dac", "out")
|
|
print(dac2out)
|
|
|
|
print("final result:", svr2dac * dac2fft * fft2out + svr2fft * fft2dac * dac2out)
|