From a37c3e6736ba3e0a3f8ca70df34f8c29a36d7307 Mon Sep 17 00:00:00 2001 From: Manoj kumar Date: Mon, 13 Oct 2025 15:21:57 +0530 Subject: [PATCH] =?UTF-8?q?Create=20Dijkstra=E2=80=99s=20Algorithm=20(Shor?= =?UTF-8?q?test=20Path=20in=20Weighted=20Graph).py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ithm (Shortest Path in Weighted Graph).py" | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 "Dijkstra\342\200\231s Algorithm (Shortest Path in Weighted Graph).py" 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'))