Skip to content

Instantly share code, notes, and snippets.

@Alwinfy
Last active December 10, 2023 16:44
Show Gist options
  • Save Alwinfy/9e5933a8bccdd4e153a8c39a2fb3b5ad to your computer and use it in GitHub Desktop.
Save Alwinfy/9e5933a8bccdd4e153a8c39a2fb3b5ad to your computer and use it in GitHub Desktop.
deeply silly day
pipe_types = {
"-": [(-1, 0), (1, 0)],
"|": [(0, -1), (0, 1)],
"7": [(-1, 0), (0, 1)],
"F": [(-1, 0), (0, -1)],
"J": [(1, 0), (0, 1)],
"L": [(1, 0), (0, -1)],
}
def nbrs(pos):
x, y = pos
yield x, y + 1
yield x, y - 1
yield x + 1, y
yield x - 1, y
def make_terrain(tmap):
connections = {}
start = None
for i, line in enumerate(tmap):
for j, char in enumerate(line):
pos = i, j
if char == "S":
start = pos
continue
conns = connections.setdefault(pos, set(nbrs(pos)))
for dx, dy in pipe_types.get(char, ()):
new_pos = i + dx, j + dy
conns.discard(new_pos)
connections.setdefault(new_pos, set(nbrs(new_pos))).discard(pos)
return connections, start, (i + 1, j + 1)
def floodfill(conns, start):
queue = [(start, 0)]
ix = 0
out = {}
while ix < len(queue):
pos, dist = queue[ix]
ix += 1
if pos in out: continue
out[pos] = dist
queue += [(nbr, dist + 1) for nbr in conns.get(pos, ())]
return out
def scan(dims, terrain, boundary):
h, w = dims
count = 0
for i in range(h):
low, high = False, False
for j in range(w):
pos = i, j
if pos in boundary:
nbrs = terrain[pos]
low ^= (i - 1, j) in nbrs
high ^= (i + 1, j) in nbrs
elif low and high:
count += 1
return count
with open("day10.in", "r") as fh:
tmap = list(map(str.strip, fh))
terrain, start, dims = make_terrain(tmap)
boundary = floodfill(terrain, start)
print(max(boundary.values()))
print(scan(dims, terrain, boundary))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment