• [^] # Re: Un grand classique, mais toujour aussi long à résoudre

    Posté par . En réponse au message Advent of Code 2023 : Jour 10. Évalué à 1.

    J'avais aussi commencé par une fonction récursive, mais elle ne dépassait la limite de recursion, je l'ai remplacé par une simple boucle while.

    inputs = open(f'input_d10.txt').read()
    grid=[]
    for y,l in enumerate(inputs.strip().split('\n')):
     if 'S' in l:
     start = l.find('S'), y
     grid.append([*l])
    H,W = len(grid)-1, len(grid[0])-1
    pipes = {
     '|': ((0,1),(0,-1)), 
     '-': ((1,0),(-1,0)),
     'L': ((0,-1),(1,0)),
     'J': ((0,-1),(-1,0)),
     '7': ((-1,0),(0,1)),
     'F': ((1,0),(0,1)),
     '.': ((0,0),(0,0))
    }
    dirs = {s:{i:o, o:i} for s,(i,o) in pipes.items()}
    def loop(dx,dy,x,y):
     l, path = 0, []
     while 1:
     if l and (x,y) == start:
     return l, path
     path.append((x,y))
     nx, ny = x+dx, y+dy
     if nx<0>ny or nx>W or ny>H:
     return None
     d = [(ndx,ndy) for dxy in map(dirs.get,grid[ny][nx]) 
     for (ndx,ndy) in dxy if (nx+ndx,ny+ndy)==(x,y)]
     if not d:
     return None
     ndx, ndy = dirs[grid[ny][nx]][d[0]]
     dx, dy, x, y, l = ndx, ndy, nx, ny, l+1
    ll, path = 0, []
    s = ''
    for p in pipes:
     x,y = start
     dx, dy = pipes[p][0]
     grid[y][x] = p
     if lp:=loop(dx,dy,x,y):
     if lp[0]>ll:
     ll, path = lp
     s = p
    part_1 = ll // 2
    print(f"{part_1=}")
    part_2 = 0
    x,y = path[0]
    grid[y][x] = s 
    path = set(path)
    prev_l = '.' * (W+1)
    for y,l in enumerate(grid):
     inside = 0
     for x,c in enumerate(l):
     if ((x,y) in path and (c=='|' or 
     (c in 'JL' and prev_l[x] in '|7F'))):
     inside ^= 1
     elif (x,y) not in path:
     part_2 += inside
     prev_l = l
    print(f"{part_2=}")