20_race.py 898 B

12345678910111213141516171819202122232425
  1. #!/usr/bin/env python3
  2. import sys
  3. def parse_track(f):
  4. grid = [line.rstrip() for line in f]
  5. x, y = next((x, y) for y, row in enumerate(grid)
  6. for x, cell in enumerate(row) if cell == 'S')
  7. track = [None, (x, y)]
  8. while grid[y][x] != 'E':
  9. x, y = next(nb for nb in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1))
  10. if nb != track[-2] and grid[nb[1]][nb[0]] != '#')
  11. track.append((x, y))
  12. return track[1:]
  13. def cheats(track, max_dist):
  14. for (t1, (x1, y1)) in enumerate(track):
  15. for t2 in range(t1 + 3, len(track)):
  16. x2, y2 = track[t2]
  17. dist = abs(x2 - x1) + abs(y2 - y1)
  18. if dist <= max_dist and t2 - t1 > dist:
  19. yield t2 - t1 - dist
  20. track = parse_track(sys.stdin)
  21. print(sum(saved >= 100 for saved in cheats(track, 2)))
  22. print(sum(saved >= 100 for saved in cheats(track, 20)))