import matrix
import shared
from collections import defaultdict
 
START = 'start'
END = 'end'

class Passage:
    def __init__(self, name):
        self.load(name)
        self.parse_connections()


    def load(self, name):
        lines= []
        with open(name, 'r') as f:
            for line in f.readlines():
                lines.append(line.rstrip())
        self.instructions = lines 

    def parse_connections(self):
        connections = defaultdict(list)
        for edge in self.instructions:
            node1, node2 = edge.split('-')
            # Add bidirectional
            connections[node1].append(node2)
            connections[node2].append(node1)
        self.connections = connections
        
    def traverse(self, multiple_entry, enter=START, seen={START}):
        if enter == END: # we're done!
            yield 1
            return

        for node in self.connections[enter]:
            if node.islower():
                if node not in seen:
                    yield from self.traverse(multiple_entry, node, seen | {node})
                elif multiple_entry and node not in {START, END}:
                    yield from self.traverse(False, node, seen | {node})
            else:
                yield from self.traverse(multiple_entry, node, seen)

def main():
    p = Passage(shared.get_fname(12))
    print(sum(p.traverse(multiple_entry=False)))
    print(sum(p.traverse(multiple_entry=True)))


if __name__ == "__main__":
    main()
