codeFlowType:
codeWrite
codeFlowLang:
Python
Напиши сложныйц код
Вот пример сложного кода на Python, который реализует алгоритм Дейкстры для поиска кратчайшего пути в графе:
import heapq
class Graph:
def __init__(self):
self.vertices = {}
def add_edge(self, from_vertex, to_vertex, weight):
if from_vertex not in self.vertices:
self.vertices[from_vertex] = []
self.vertices[from_vertex].append((to_vertex, weight))
def dijkstra(self, start_vertex):
# Словарь для хранения минимальных расстояний до каждого вершин
distances = {vertex: float('infinity') for vertex in self.vertices}
distances[start_vertex] = 0
# Очередь с приоритетом для выбора вершин с наименьшим расстоянием
priority_queue = [(0, start_vertex)]
while priority_queue:
current_distance, current_vertex = heapq.heappop(priority_queue)
# Если текущее расстояние больше, чем уже известное, пропускаем
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in self.vertices[current_vertex]:
distance = current_distance + weight
# Если найдено более короткое расстояние до соседней вершины
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances
# Пример использования
graph = Graph()
graph.add_edge('A', 'B', 1)
graph.add_edge('A', 'C', 4)
graph.add_edge('B', 'C', 2)
graph.add_edge('B', 'D', 5)
graph.add_edge('C', 'D', 1)
distances = graph.dijkstra('A')
print("Минимальные расстояния от вершины A:", distances)