hicharlotte

Untitled

Dec 15th, 2022
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. from dijkstar import Graph, find_path
  2.  
  3. #Build a list of entries
  4. input = 'day12_input.txt'
  5. forest = []
  6. file1 = open(input, 'r')
  7. lines = file1.readlines()
  8. for i,row in enumerate(lines):
  9. row = row.strip()
  10. this_row = []
  11. for j, char in enumerate(row):
  12. this_row.append(char)
  13. forest.append(this_row)
  14. print(forest)
  15.  
  16. def getHeight(input):
  17. if input == 'S': input = 'a'
  18. elif input == 'E': input = 'z'
  19. return ord(input)
  20.  
  21. def getName(input,i,j):
  22. return input +str(i)+str(j)
  23.  
  24. graph = Graph()
  25. for i,row in enumerate(forest):
  26. for j,char in enumerate(row):
  27. this_val = forest[i][j]
  28. if this_val == 'S': start_node = getName(this_val,i,j)
  29. if this_val == 'E': end_node = getName(this_val, i,j)
  30.  
  31. if i >0:
  32. next_val = forest[i-1][j]
  33. if getHeight(next_val) - getHeight(this_val)<=1:
  34. graph.add_edge(getName(this_val,i,j), getName(next_val, i-1, j),1)
  35.  
  36. if i < len(forest)-1:
  37. next_val = forest[i+1][j]
  38. if getHeight(next_val) - getHeight(this_val)<=1:
  39. graph.add_edge(getName(this_val,i,j), getName(next_val, i+1,j),1)
  40.  
  41. if j >0:
  42. next_val = forest[i][j-1]
  43. if getHeight(next_val) - getHeight(this_val) <=1:
  44. graph.add_edge(getName(this_val,i,j), getName(next_val, i, j-1), 1)
  45.  
  46. if j < len(row)-1:
  47. next_val = forest[i][j+1]
  48. if getHeight(next_val)- getHeight(this_val)<=1:
  49. graph.add_edge(getName(this_val, i, j), getName(next_val, i, j+1), 1)
  50.  
  51. path_info_res = find_path(graph, start_node, end_node)
  52. print(path_info_res.total_cost)
  53.  
Advertisement
Add Comment
Please, Sign In to add comment