#!/usr/bin/env python # 2024 - Advent Of Code 6 - part 2 # file = 'input_example.txt' file = 'input.txt' input_lines = [] with open(file, encoding="utf-8") as f: for l in f.readlines(): input_lines.append(list(l.strip())) MAX_X = len(input_lines[0]) MAX_Y = len(input_lines) vector=(0, 0) gx = 0 gy = 0 for y in range(0, MAX_Y): for x in range(0, MAX_X): g = input_lines[y][x] if g not in ('.', '#'): gx = x gy = y print(f'found guard at {x}, {y}') if g == '^': vector = (0, -1) if g == 'v': vector = (0, 1) if g == '>': vector = (1, 0) if g == '<': vector = (-1, 0) print(f'{vector=}') moves = [(0,-1), (1, 0), (0, 1), (-1, 0)] move = moves.index(vector) def move_and_detect(grid, posx, posy, v, m): visited = [(posx, posy, v)] while 0 < posx < MAX_X and 0 < posy < MAX_Y: nx = posx + v[0] ny = posy + v[1] if nx < 0 or nx >= MAX_X or ny < 0 or ny >= MAX_Y: return False if grid[ny][nx] != '#': posx += v[0] posy += v[1] if (posx, posy, v) in visited: return True visited.append((posx, posy, v)) else: m += 1 v = moves[m % 4] return False start_gx = gx start_gy = gy start_vector = vector start_move = move found_loop = set() while 0 <= gx < MAX_X and 0 <= gy < MAX_Y: nextx = gx + vector[0] nexty = gy + vector[1] if nextx < 0 or nextx >= MAX_X or nexty < 0 or nexty >= MAX_Y: break if input_lines[nexty][nextx] != '#': # print(f'testing bloc at {nextx}, {nexty}') old_value = input_lines[nexty][nextx] input_lines[nexty][nextx] = '#' if (nextx, nexty) not in found_loop: if move_and_detect(input_lines, start_gx, start_gy, start_vector, start_move): print(f'found loop with bloc at {nextx}, {nexty}') found_loop.add((nextx, nexty)) input_lines[nexty][nextx] = old_value gx = nextx gy = nexty else: move += 1 vector = moves[move % 4] # print(f'new vector: {vector}') print(f'{len(found_loop)=}')