diff --git "a/Dijkstra\342\200\231s Algorithm (Shortest Path in Weighted Graph).py" "b/Dijkstra\342\200\231s Algorithm (Shortest Path in Weighted Graph).py" new file mode 100644 index 000000000000..822a7c1add81 --- /dev/null +++ "b/Dijkstra\342\200\231s Algorithm (Shortest Path in Weighted Graph).py" @@ -0,0 +1,31 @@ +import heapq + +def dijkstra(graph, start): + distances = {node: float('inf') for node in graph} + distances[start] = 0 + pq = [(0, start)] + + while pq: + current_distance, current_node = heapq.heappop(pq) + + if current_distance > distances[current_node]: + continue + + for neighbor, weight in graph[current_node].items(): + distance = current_distance + weight + if distance < distances[neighbor]: + distances[neighbor] = distance + heapq.heappush(pq, (distance, neighbor)) + + return distances + + +# Example graph (dictionary) +graph = { + 'A': {'B': 1, 'C': 4}, + 'B': {'A': 1, 'C': 2, 'D': 5}, + 'C': {'A': 4, 'B': 2, 'D': 1}, + 'D': {'B': 5, 'C': 1} +} + +print(dijkstra(graph, 'A'))