import heapq def solve(input): G = {} V = [] for line in open(input): parts = line.split() v = parts.pop(0).strip(':') V.append(v) G[v] = parts extra = [e for edges in G.values() for e in edges if e not in V] V += extra for v in extra: G[v] = [] Q = [(0,'you')] dist = {} paths = {v:0 for v in V} paths['you'] = 1 while Q: cost, v = heapq.heappop(Q) if v in dist: continue dist[v] = cost for e in G[v]: if e not in dist: heapq.heappush(Q, (cost+1, e)) paths[e] += paths[v] print(paths) print(paths['out']) solve("sample") solve("input")