day 10 cleanup, make fill slighly more efficient

main
magical 2023-12-10 06:43:32 +00:00
parent c111075e16
commit 3ba6804013
1 changed files with 21 additions and 17 deletions

View File

@ -1,6 +1,6 @@
import sys
from collections import defaultdict
map = [list(x.strip()) for x in sys.stdin]
map = [x.strip() for x in sys.stdin]
print(map)
@ -29,8 +29,14 @@ for i, row in enumerate(map):
raise Exception("invalid char %s at (%s,%s)" % (c, i, j))
grid[i,j] = d
print(grid)
#print(grid)
def draw(grid):
y = max([i for i,j in grid.keys()])
x = max([j for i,j in grid.keys()])
for i in range(y+1):
print("".join(".+O"[grid[i,j]] if (i,j) in grid else "x" for j in range(x+1)))
print()
def find_loop(grid, start):
front = [(0,start)]
@ -70,7 +76,7 @@ def enclosedby(grid, points):
for k in range(3):
for l in range(3):
fill[i*3+k,j*3+l] = 0
print(*sorted(fill.keys()), sep="\n")
#print(*sorted(fill.keys()), sep="\n")
for i,j in points:
d = grid[i,j]
if d == N|S: t=[[0,1,0],[0,1,0],[0,1,0]]
@ -83,7 +89,7 @@ def enclosedby(grid, points):
for k in range(3):
for l in range(3):
fill[i*3+k,j*3+l] = t[k][l]
print(fill)
#print(fill)
# fill edges
for i in range(Y*3):
@ -94,25 +100,23 @@ def enclosedby(grid, points):
if fill[Y*3-1,j] == 0: fill[Y*3-1,j] = 2
# flood fill
def set(i,j):
if (i,j) in fill:
if fill[i,j] == 0:
next[i,j] = 2
while True:
#for i in range(Y*3):
#print("".join(".+O"[fill[i,j]] for j in range(X*3)))
next = fill.copy()
def set(i,j):
if (i,j) in fill:
if fill[i,j] == 0:
next[i,j] = 2
#draw(fill)
next = {}
for i,j in fill:
if fill[i,j] == 2:
set(i-1,j)
set(i+1,j)
set(i,j-1)
set(i,j+1)
if next == fill:
if not next:
break
fill = next
for i in range(Y*3):
print("".join(".+O"[fill[i,j]] for j in range(X*3)))
fill.update(next)
draw(fill)
# downsample
inside = []
@ -122,13 +126,13 @@ def enclosedby(grid, points):
inside.append((i,j))
print(inside)
print("inside =", inside)
return len(inside)
for D in [W|S, N|W, N|E, S|E, N|S, W|E]:
grid[start] = D
loop = find_loop(grid, start)
if loop:
print(D, loop)
print(D, loop.keys())
print(max(loop.values()))
print(enclosedby(grid, loop))