Advertisement
Guest User

Day 23 part two

a guest
Dec 23rd, 2023
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | Source Code | 0 0
  1. from collections import defaultdict
  2. maze_graph=defaultdict(set)
  3. the_plan=[j.strip() for j in open("23.txt")]
  4. directions={(0,-1):'^',(0,1):'v',(-1,0):'<',(1,0):'>'}
  5. start=the_plan[0].find('.')
  6. end=the_plan[-1].find('.')
  7. pos=[[(start,0),(0,1),(start,1)]]
  8. ans=[]
  9. def avail(point,direction):
  10.         direct=directions.copy()
  11.         out=[]
  12.         direct.pop((direction[0]*-1,direction[1]*-1))
  13.         for d in direct:
  14.             out.append([(point[0]+d[0],point[1]+d[1]),d])
  15.         return list(filter(lambda x: the_plan[x[0][1]][x[0][0]]!='#',out))
  16. def new_path_helper(list_of_pos):
  17.      for i in list_of_pos:
  18.         point,direction=i
  19.         if the_plan[point[1]][point[0]]==directions[direction] or the_plan[point[1]][point[0]]=='.':
  20.             yield i
  21. def bfs():
  22.     queue=[]
  23.     ans=[]
  24.     queue.append((1,maze_graph[(start,0)]))
  25.     while queue:
  26.         length,nodes=queue.pop(0)
  27.         for node in nodes:
  28.             l,point=node
  29.             queue.append((length+l,maze_graph[point]))
  30.         if len(nodes)==0:
  31.             ans.append(length)
  32.     return(ans)
  33.  
  34. def recursive_longest_path(start,length,visited=[]):
  35.     next_visited=visited.copy()
  36.     next_visited.append(start)
  37.     initial=maze_graph[start]
  38.     working=[]
  39.     for l,node in initial:
  40.         if node not in visited:
  41.             working.append((l,node))
  42.         if node==(end,len(the_plan)-1):
  43.             ans.append(l+length)
  44.             return
  45.     for l,node in working:
  46.         recursive_longest_path(node,length+l,next_visited)
  47. for i in pos:
  48.     origin,direction,point=i
  49.     length=0
  50.     while True:
  51.         if point==(end,len(the_plan)-1):
  52.                 maze_graph[origin].add((length,point))
  53.                 break
  54.         new=avail(point,direction)
  55.         length+=1
  56.         if len(new)==1:
  57.             point,direction=new[0]
  58.         else:
  59.             maze_graph[origin].add((length,point))
  60.             for j in new:
  61.                 if [point,j[1],j[0]] not in pos:
  62.                     pos.append([point,j[1],j[0]])
  63.             break
  64. recursive_longest_path((start,0),1)
  65. print(max(ans))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement