No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

35 líneas
980B

  1. import heapq
  2. def shortest_path(graph, start, end):
  3. risk_sum = {start: 0}
  4. heap = [(0, *start)]
  5. while end not in risk_sum:
  6. risk, x, y = heapq.heappop(heap)
  7. for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
  8. adj = (x + dx, y + dy)
  9. if adj in graph:
  10. if adj not in risk_sum or risk_sum[adj] > graph[adj] + risk:
  11. risk_sum[adj] = graph[adj] + risk
  12. heapq.heappush(heap, (risk_sum[adj], x + dx, y + dy))
  13. return risk_sum[end]
  14. graph = {}
  15. for y, line in enumerate(open(0).read().splitlines()):
  16. for x, char in enumerate(line):
  17. graph[x, y] = int(char)
  18. X, Y = x + 1, y + 1
  19. ans1 = shortest_path(graph, min(graph), max(graph))
  20. print(ans1)
  21. graph = {
  22. (x + X * dx, y + Y * dy): sum(divmod(graph[x, y] + dx + dy, 10))
  23. for (x, y), value in graph.items()
  24. for dx in range(5)
  25. for dy in range(5)
  26. }
  27. ans2 = shortest_path(graph, min(graph), max(graph))
  28. print(ans2)