def follow_path(map_):
x, y = map_[0].index("|"), 0
dx, dy = 0, 1
steps = 0
found = []
while True:
steps += 1
x, y = x + dx, y + dy
mapchar = map_[y][x]
if mapchar == " " or not 0 <= x < len(map_[0]) or not 0 <= y < len(map_):
# map end found
return "".join(found), steps
if mapchar.isalpha():
found.append(mapchar)
elif mapchar == "+":
# direction change, find new
if dx:
dx, dy = 0, 1 if map_[y - 1][x] == " " else -1
else:
dx, dy = 1 if map_[y][x - 1] == " " else -1, 0
word, steps = follow_path(
[
" | ",
" | +--+ ",
" A | C ",
" F---|----E|--+ ",
" | | | D ",
" +B-+ +--+ ",
]
)
assert word == "ABCDEF"
assert steps == 38
import aocd
data = aocd.get_data(day=19, year=2017)
map_ = data.splitlines()
word, steps = list(follow_path(map_))
print("Part 1:", word)
print("Part 2:", steps)
Part 1: AYRPVMEGQ Part 2: 16408