Day 10 - Advent of Code 2023

Working solutions for the day 10 puzzles.

Part One

""" day_10_01.py """

# usage: python3 day_10_01.py < input

import sys


deltas = {'n': (-1, 0), 'e': (0, 1), 'w': (0, -1), 's': (1, 0), '.': (0, 0)}


def look(u, pos):
    """ what's there """
    r, c = deltas[u][0] + pos[0], deltas[u][1] + pos[1]
    if 0 <= r < size and 0 <= c < size:
        return maze[r * size + c]
    return '.'


connect = {'|': {'n': '|F7', 'e': '', 'w': '', 's': 'L|J'},
           '-': {'n': '', 'e': '-7J', 'w': '-LF', 's': ''},
           'L': {'n': '|F7', 'e': '-7J', 'w': '', 's': ''},
           'J': {'n': '|F7', 'e': '', 'w': '-LF', 's': ''},
           '7': {'n': '', 'e': '', 'w': '-LF', 's': 'L|J'},
           'F': {'n': '', 'e': '-7J', 'w': '', 's': 'L|J'},
           '.': {'n': '', 'e': '', 'w': '', 's': ''}}

maze = []
size = 0
for line in sys.stdin:
    maze.extend(line.rstrip())
    size += 1

start = divmod(maze.index('S'), size)
pipe = [set(connect[look(i, start)][j])
        for i, j in [['n', 's'], ['e', 'w'], ['w', 'e'], ['s', 'n']]
        if connect[look(i, start)][j]]
maze[maze.index('S')] = set.intersection(*pipe).pop()

path = []
x = start
while start not in path:
    for i in ['n', 'e', 'w', 's']:
        if look(i, x) in connect[look('.', x)][i]:
            next_x = deltas[i][0] + x[0], deltas[i][1] + x[1]
            if next_x in path:
                continue
            break
    x = next_x
    path.append(x)

print(len(path) // 2)

Part Two