fork download
  1. from collections import deque
  2.  
  3. def main():
  4. data = list(map(int, input().split()))
  5. data = [x - 1 for x in data]
  6.  
  7. n, k, l = data[:3]
  8. n += 1
  9. k += 1
  10. l += 1
  11.  
  12. teleports = []
  13. walls = set()
  14.  
  15. index = 3
  16. for _ in range(k):
  17. arr1 = tuple(data[index:index+3])
  18. arr2 = tuple(data[index+3:index+6])
  19. teleports.append((arr1, arr2))
  20. index += 6
  21.  
  22. for _ in range(l):
  23. walls.add(tuple(data[index:index+3]))
  24. index += 3
  25.  
  26. start_cords = tuple(data[index:index+3])
  27. index += 3
  28. goal_cords = tuple(data[index:index+3])
  29.  
  30. directions = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)]
  31.  
  32. deck = deque([(start_cords, 0)])
  33. visited = set()
  34. visited.add(start_cords)
  35.  
  36. while deck:
  37. curr, dist = deck.popleft()
  38. x,y,z = curr
  39.  
  40. if curr == goal_cords:
  41. print(dist)
  42. return
  43.  
  44. for teleport_pair in teleports:
  45. linked_teleport = None
  46. if curr == teleport_pair[0]:
  47. linked_teleport = teleport_pair[1]
  48. elif curr == teleport_pair[1]:
  49. linked_teleport = teleport_pair[0]
  50.  
  51. if linked_teleport and linked_teleport not in visited:
  52. visited.add(linked_teleport)
  53. deck.appendleft((linked_teleport, dist))
  54.  
  55. for dx, dy, dz in directions:
  56. new_x, new_y, new_z = x + dx, y + dy, z + dz
  57. if 0 <= new_x < n and 0 <= new_y < n and 0 <= new_z < n:
  58. neybor = (new_x, new_y, new_z)
  59. if neybor not in walls and neybor not in visited:
  60. visited.add(neybor)
  61. deck.append((neybor, dist + 1))
  62.  
  63. print(-1)
  64.  
  65. main()
Success #stdin #stdout 0.04s 9840KB
stdin
10 40 0 2 1 4 1 1 4 3 3 4 1 1 4 2 1 1 3 2 1 3 2 2 2 2 2 2 3 4 3 2 1 2 2 4 3 1 4 2 1 1 2 3 2 2 3 3 3 3 2 3 2 2 1 4 2 4 4 3 3 2 2 3 1 3 3 4 3 2 3 3 1 2 1 3 1 1 4 4 4 1 4 3 3 1 1 1 3 4 1 2 2 1 2 3 4 4 2 1 2 1 3 3 1 2 1 2 4 3 2 1 4 2 3 2 3 3 4 3 1 2 4 2 1 2 4 3 1 4 1 4 1 1 1 2 2 2 1 3 2 3 1 4 2 1 2 3 2 3 2 3 3 3 3 3 4 3 2 3 2 4 4 1 3 3 3 2 3 3 3 4 4 3 3 1 3 3 2 2 4 3 2 1 2 4 3 2 2 2 3 4 1 1 3 3 4 1 2 4 4 2 4 2 4 3 4 2 4 3 4 2 4 2 2 3 4 1 1 4 3 1 2 1 2 4 4 3 2 2 1 3 4 3 1 4 2 2 3 3 3 1 3 9 10 9 1 1 3
stdout
19