Advertisement
Guest User

Day 23 part one

a guest
Dec 23rd, 2023
216
0
17 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 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. def avail(point,direction):
  9.         direct=directions.copy()
  10.         out=[]
  11.         direct.pop((direction[0]*-1,direction[1]*-1))
  12.         for d in direct:
  13.             out.append([(point[0]+d[0],point[1]+d[1]),d])
  14.         return list(filter(lambda x: the_plan[x[0][1]][x[0][0]]!='#',out))
  15. def new_path_helper(list_of_pos):
  16.      for i in list_of_pos:
  17.         point,direction=i
  18.         if the_plan[point[1]][point[0]]==directions[direction] or the_plan[point[1]][point[0]]=='.':
  19.             yield i
  20. def bfs():
  21.     queue=[]
  22.     ans=[]
  23.     queue.append((1,maze_graph[(start,0)]))
  24.     while queue:
  25.         length,nodes=queue.pop(0)
  26.         for node in nodes:
  27.             l,point=node
  28.             queue.append((length+l,maze_graph[point]))
  29.         if len(nodes)==0:
  30.             ans.append(length)
  31.     return(ans)
  32.  
  33. for i in pos:
  34.     origin,direction,point=i
  35.     length=0
  36.     while True:
  37.         if point==(end,len(the_plan)-1):
  38.                 maze_graph[origin].add((length,point))
  39.                 break
  40.         new=avail(point,direction)
  41.         length+=1
  42.         if len(new)==1:
  43.             point,direction=new[0]
  44.         else:
  45.             maze_graph[origin].add((length,point))
  46.             new=new_path_helper(new)
  47.             for j in new:
  48.                 if [point,j[1],j[0]] not in pos:
  49.                     pos.append([point,j[1],j[0]])
  50.                 else:
  51.                     break
  52.             break
  53. print(max(bfs()))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement