16_maze.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/env python3
  2. import sys
  3. from heapq import heappop, heappush
  4. grid = [line.rstrip() for line in sys.stdin]
  5. start = next((x, y) for y, row in enumerate(grid)
  6. for x, cell in enumerate(row) if cell == 'S')
  7. end = next((x, y) for y, row in enumerate(grid)
  8. for x, cell in enumerate(row) if cell == 'E')
  9. work = [(0, (start,), 1, 0)]
  10. best_costs = {(*start, 1, 0): 0}
  11. best_end_cost = 0
  12. best_seats = set()
  13. while work:
  14. cost, path, dx, dy = heappop(work)
  15. x, y = pos = path[-1]
  16. if pos == end:
  17. best_seats |= {*path}
  18. best_end_cost = cost
  19. elif not best_end_cost or cost < best_end_cost:
  20. for cost, x, y, dx, dy in (
  21. (cost + 1, x + dx, y + dy, dx, dy), # straight
  22. (cost + 1000, x, y, dy, -dx), # left
  23. (cost + 1000, x, y, -dy, dx), # right
  24. ):
  25. pos = x, y, dx, dy
  26. if grid[y][x] != '#' and best_costs.get(pos, cost + 1) >= cost:
  27. best_costs[pos] = cost
  28. heappush(work, (cost, path + ((x, y),), dx, dy))
  29. print(best_end_cost)
  30. print(len(best_seats))