Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

50 lines
1.1KB

  1. import sys
  2. from itertools import permutations
  3. text = sys.stdin.read()
  4. # transform text into data structures
  5. valid = set()
  6. target = {}
  7. for y, line in enumerate(text.splitlines()):
  8. for x, char in enumerate(line):
  9. if char == '#':
  10. continue
  11. valid.add(x + 1j * y)
  12. if char != '.':
  13. target[x + 1j * y] = char
  14. # generate travel map
  15. graph = {}
  16. for A in target:
  17. seen = {A}
  18. boundary = {A}
  19. pending = set(target) - seen
  20. N = 0
  21. while pending:
  22. N += 1
  23. boundary = {pos + step for pos in boundary for step in [1, -1, 1j, -1j]}
  24. boundary &= valid - seen
  25. seen.update(boundary)
  26. for B in boundary & pending:
  27. pending -= {B}
  28. graph[target[A], target[B]] = N
  29. # use map to determine routes
  30. calc = lambda combo: sum(graph[pair] for pair in zip(combo, combo[1:]))
  31. z = '0'
  32. rest = set(target.values()) - {z}
  33. options = [(z,) + combo for combo in permutations(rest)]
  34. ans = min(options, key=calc)
  35. print(calc(ans))
  36. options = [(z,) + combo + (z,) for combo in permutations(rest)]
  37. ans = min(options, key=calc)
  38. print(calc(ans))