khuseiN

Untitled

Mar 15th, 2023
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. import random
  2. import heapq
  3.  
  4. # Создаем случайный граф
  5. graph = {i: {} for i in range(1, 12)}
  6. for v in [2, 3, 4]:
  7. graph[1][v] = random.randint(1, 10)
  8. for i in range(2, 12):
  9. for j in range(i + 1, 12):
  10. if random.random() < 0.3:
  11. graph[i][j] = graph[j][i] = random.randint(1, 10)
  12.  
  13. print("Граф:")
  14. print(graph)
  15.  
  16. def dijkstra(graph, start, end):
  17. distances = {vertex: float('inf') for vertex in graph}
  18. distances[start] = 0
  19. visited = set()
  20. queue = [(0, start)]
  21. path = {}
  22.  
  23. while queue:
  24. (current_distance, current_vertex) = heapq.heappop(queue)
  25. if current_vertex == end:
  26. # Формируем путь в обратном порядке
  27. path_list = [end]
  28. while end != start:
  29. path_list.append(path[end])
  30. end = path[end]
  31. path_list.reverse()
  32. return (path_list, distances[current_vertex])
  33. if current_vertex in visited:
  34. continue
  35. visited.add(current_vertex)
  36.  
  37. for neighbor, weight in graph[current_vertex].items():
  38. distance = current_distance + weight
  39. if distance < distances[neighbor]:
  40. distances[neighbor] = distance
  41. path[neighbor] = current_vertex
  42. heapq.heappush(queue, (distance, neighbor))
  43.  
  44. return (path, distances[end])
  45.  
  46. # Находим кратчайший путь от вершины 1 до вершины 11
  47. path, distance = dijkstra(graph, 1, 11)
  48. print("Кратчайший путь:", path)
  49. print("Длина пути:", distance)
Advertisement
Add Comment
Please, Sign In to add comment