39 lines
1013 B
Python
39 lines
1013 B
Python
from day07.common import BaseGraph
|
|
|
|
|
|
class Graph(BaseGraph):
|
|
|
|
def depth_first_search(self, start: str, search_contained_by: bool = False):
|
|
visited = []
|
|
|
|
def count_bags(nxt):
|
|
if nxt not in self._nodes:
|
|
return 0
|
|
node = self._nodes[nxt]
|
|
if node.visited:
|
|
return node.count
|
|
node.visited = True
|
|
visited.append(node)
|
|
iter_over = node.contained_by if search_contained_by else node.contains
|
|
cnt = sum(val*count_bags(key) for key, val in iter_over.items()) + 1
|
|
node.count = cnt
|
|
return cnt
|
|
|
|
overall_cnt = count_bags(start)
|
|
for visit in visited:
|
|
visit.visited = False
|
|
visit.count = 0
|
|
return overall_cnt
|
|
|
|
|
|
graph = Graph()
|
|
lines = (x.strip() for x in open("input.txt"))
|
|
count = -1
|
|
|
|
for line in lines:
|
|
graph.add_line(line)
|
|
|
|
count = graph.depth_first_search("shiny gold", search_contained_by=False) - 1
|
|
|
|
print(count)
|