import re
from tracemalloc import start
import numpy as np

f = open('input.txt', 'r')
my_graph = dict(dict())
content = f.read()
lines = content.splitlines()
instructions = []

for line_count, line in enumerate(lines):
    if line_count == 0:
        instructions = line
    else:
        numbers = re.findall(r'[A-Za-z]+', line)
        if len(numbers) == 3:
            
            my_graph[numbers[0]] = {"L": numbers[1], "R": numbers[2]}
    
print(my_graph)

starting_key = 'AAA'
ending_key = 'ZZZ'
inst_idx = 0
steps = 0

current_key = starting_key
while current_key != ending_key:
    current_key = my_graph[current_key][instructions[inst_idx]]
    steps += 1
    inst_idx = (inst_idx + 1)%len(instructions)

print(steps)


f.close()