您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

38 行
983B

  1. import heapq
  2. def shortest_path(graph, X, Y):
  3. risk = {0: 0}
  4. seen = set()
  5. heap = [(0, '', 0)] # string disambiguates cost ties for imaginary numbers
  6. end = complex(X - 1, Y - 1)
  7. tip = 0
  8. while end not in seen:
  9. _, _, tip = heapq.heappop(heap)
  10. seen.add(tip)
  11. for y in (tip + dx for dx in [1, -1, 1j, -1j]):
  12. if y in graph:
  13. if y not in risk or risk[y] > graph[y] + risk[tip]:
  14. risk[y] = graph[y] + risk[tip]
  15. heapq.heappush(heap, (risk[y], str(y), y))
  16. return risk[end]
  17. graph = {}
  18. for y, line in enumerate(text.splitlines()):
  19. for x, char in enumerate(line):
  20. graph[complex(x, y)] = int(char)
  21. X, Y = x + 1, y + 1
  22. ans1 = shortest_path(graph, X, Y)
  23. graph = {
  24. pos + complex(X * dx, Y * dy): sum(divmod(graph[pos] + dx + dy, 10))
  25. for pos, value in graph.items()
  26. for dx in range(5)
  27. for dy in range(5)
  28. }
  29. ans2 = shortest_path(graph, 5 * X, 5 * Y)