Solutions to Advent of Code 2017 https://adventofcode.com/2017/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1234567891011121314151617181920212223242526272829303132333435
  1. import operator
  2. def junction_routes(maze, pos):
  3. dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
  4. for dir in dirs:
  5. new_pos = tuple(map(operator.add, pos, dir))
  6. try:
  7. cell = maze[new_pos[1]][new_pos[0]]
  8. if cell.isalpha() or cell in ['|', '-', '+']:
  9. yield dir
  10. except:
  11. # Out of bounds
  12. pass
  13. with open('data/19.txt', 'r') as file:
  14. maze = file.readlines()
  15. p, d, h, cell = (maze[0].index('|'), 0), (0, 1), [], '|'
  16. # Steps doesn't include the starting step, but does include an extra step at the end
  17. # where we step into whitespace, so balances out.
  18. steps = 0
  19. while cell != ' ':
  20. p = tuple(map(operator.add, p, d))
  21. cell = maze[p[1]][p[0]]
  22. steps += 1
  23. if cell == '+':
  24. d = next(o for o in junction_routes(maze, p) if o != (-d[0], -d[1]))
  25. elif cell.isalpha():
  26. h.append(cell)
  27. print(f'Part one: {"".join(h)}')
  28. print(f'Part two: {steps}')