60 lines
1.2 KiB
Python
60 lines
1.2 KiB
Python
import sys
|
|
|
|
# parse
|
|
I = sys.stdin.read().splitlines()
|
|
G = [list(l) for l in I]
|
|
W = len(G[0])
|
|
H = len(G)
|
|
|
|
# look for S
|
|
S = None
|
|
for y in range(H):
|
|
if (x := I[y].find("S")) > -1:
|
|
S = (x,y)
|
|
break
|
|
|
|
# encode moves
|
|
D = {
|
|
'u': {'|': ( 0,-1,'u'), 'F': ( 1, 0,'r'), '7': (-1, 0,'l')},
|
|
'r': {'-': ( 1, 0,'r'), 'J': ( 0,-1,'u'), '7': ( 0, 1,'d')},
|
|
'd': {'|': ( 0, 1,'d'), 'L': ( 1, 0,'r'), 'J': (-1, 0,'l')},
|
|
'l': {'-': (-1, 0,'l'), 'L': ( 0,-1,'u'), 'F': ( 0, 1,'d')},
|
|
}
|
|
|
|
# part 1
|
|
poly = [S] # vertices of the polygone
|
|
x0, y0 = S
|
|
P = (x0+1, y0, 'r') # start at S and go right
|
|
for _ in range(100_000):
|
|
x, y, d = P
|
|
poly.append((x,y))
|
|
z = G[y][x]
|
|
if z == 'S':
|
|
break
|
|
dx,dy,nd = D[d].get(z)
|
|
P = (x+dx,y+dy,nd)
|
|
print(len(poly)//2)
|
|
|
|
# part 2
|
|
from matplotlib.path import Path
|
|
|
|
pg = Path(poly)
|
|
|
|
J = [['.']*W for _ in range(H)]
|
|
R = 0
|
|
for y in range(W):
|
|
for x in range(H):
|
|
if (x,y) in poly:
|
|
J[y][x] = G[y][x]
|
|
elif pg.contains_point((x,y)):
|
|
R += 1
|
|
J[y][x] = "O"
|
|
print(R)
|
|
|
|
# plot
|
|
J[y0][x0] = "S"
|
|
T = str.maketrans("|-LJ7F", "│─└┘┐┌")
|
|
with open("grid.txt","wt") as f:
|
|
for row in J:
|
|
print("".join(row).translate(T), file=f)
|