AoC d 12 p1/2
import time start_time = time.time() filepath = '2024d12.txt' advent1file=open(filepath,'r') listoflines =[[y for y in x.strip()] for x in advent1file.readlines()] # totalcost=0 origcost=0 direct=[[0,1],[1,0],[0,-1],[-1,0]] borderDirect=[[[1,0],[-1,0]],[[0,1],[0,-1]],[[1,0],[-1,0]],[[0,1],[0,-1]]] for x in range(len(listoflines)): for y in range(len(listoflines[x])): if listoflines[x][y]!='donethat': toDo=[[listoflines[x][y],x,y]] perim=0 area=0 newsides=0 thisplot=set() existingBorder=[] while len(toDo)!=0: stillmatch,X,Y=toDo.pop() if (X,Y) in thisplot: continue area+=1 thisplot.add((X,Y)) for dnum in range(len(direct)): d=direct[dnum] if X+d[0] not in range(len(listoflines)) or Y+d[1] not in range(len(listoflines[X])) or listoflines[X+d[0]][Y+d[1]]!=stillmatch: perim+=1 existingBorder.append([dnum,X+d[0],Y+d[1]]) elif listoflines[X+d[0]][Y+d[1]]==stillmatch and (X+d[0],Y+d[1]) not in thisplot: toDo.append([stillmatch,X+d[0],Y+d[1]]) for X,Y in thisplot: listoflines[X][Y]='donethat' existingBorder.sort() for i in range(len(existingBorder)): if existingBorder[i]!='accountedfor': newsides+=1 directnum,X,Y=existingBorder[i] thisside=set() toDo=[[directnum,X,Y]] while len(toDo)!=0: [zz,X1,Y1]=toDo.pop() if (X1,Y1) in thisside: continue thisside.add((directnum,X1,Y1)) q=(directnum,X1+borderDirect[directnum][0][0],Y1+borderDirect[directnum][0][1]) if list(q) in existingBorder and q not in thisside: toDo.append(q) q=(directnum,X1+borderDirect[directnum][1][0],Y1+borderDirect[directnum][1][1]) if list(q) in existingBorder and q not in thisside: toDo.append(q) for P in thisside: existingBorder[existingBorder.index(list(P))]='accountedfor' totalcost+=(newsides*area) origcost+=(perim*area) print(totalcost) print(origcost) tim=time.time()-start_time print(tim)
Leave a Comment