day 07
handy haversacks
approach
the rules become a graph: a dictionary from each bag colour to a dictionary of the colours it holds and how many of each. part 1 runs a recursive search from every colour and counts the ones that can eventually reach shiny gold.
part 2 goes the other way: starting at shiny gold, each bag counts itself plus, for every child, the child's count times its own recursive total. the outer bag is subtracted at the end.
the trick
nested bags multiply: a bag's total is one plus each child's total times how many of it it holds.
python
def count_bags(graph, bag):
res = 1
for bb, nn in graph[bag].items():
res += nn * count_bags(graph, bb)
return res