from lib import get_data from lib import Grid2D data = get_data(__file__) DIRS = [ (-1, 0), (0, 1), (1, 0), (0, -1), ] g = Grid2D(data) t = 0 for rr in range(g.n_rows): for cc in range(g.n_cols): (p,), dir = g.find("^"), 0 seen = set() loop = False if g[(rr, cc)] == "#": continue if g[(rr, cc)] != "^": g[(rr, cc)] = "#" while True: if (p, dir) in seen: loop = True break seen.add((p, dir)) r, c = p[0] + DIRS[dir][0], p[1] + DIRS[dir][1] if not (0 <= r < g.n_rows and 0 <= c < g.n_cols): break if g[(r, c)] == "#": dir = (dir + 1) % 4 else: p = (r, c) if g[(rr, cc)] == "^": print(len(set(pos for pos, _ in seen))) else: g[(rr, cc)] = "." if loop: t += 1 print(t)