DhanushNehru / Hacktoberfest2024

Hacktoberfest 2024 OPEN FIRST Pull Request - SUPPORT OPEN SOURCE - Don't forget to spread love and if you like give us a ⭐️
84 stars 520 forks source link

Dijkstra's algorithm #70

Open Invincible1602 opened 1 month ago

Invincible1602 commented 1 month ago

Hey @DhanushNehru,

I want to implement the Dijkstra's Algorithm in Python. Dijkstra's algorithm is a greedy algorithm that finds the shortest paths in a graph with non-negative edge weights by following these steps:

Input:

Output:

Please assign me the issue and hacktoberfest label.

mukprabhakar commented 1 month ago

Python implementation of Dijkstra's Algorithm using a priority queue (min-heap) to find the shortest path in a graph with non-negative edge weights: import heapq

def dijkstra(graph, source):

Initialize the priority queue

priority_queue = []

# Initialize distances to infinity for all vertices except the source
distances = {vertex: float('infinity') for vertex in graph}
distances[source] = 0

# Push the source node into the priority queue with distance 0
heapq.heappush(priority_queue, (0, source))

while priority_queue:
    # Pop the vertex with the smallest distance
    current_distance, current_vertex = heapq.heappop(priority_queue)

    # If the current distance is greater than the recorded distance, skip it
    if current_distance > distances[current_vertex]:
        continue

    # Check adjacent vertices
    for neighbor, weight in graph[current_vertex].items():
        distance = current_distance + weight

        # Only consider this path if it's better than the known one
        if distance < distances[neighbor]:
            distances[neighbor] = distance
            # Push the updated distance and neighbor into the queue
            heapq.heappush(priority_queue, (distance, neighbor))

return distances

Example usage: 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} }

source = 'A' shortest_distances = dijkstra(graph, source) print(shortest_distances) Output: { 'A': 0, 'B': 1, 'C': 3, 'D': 4 } Explanation: Priority Queue (min-heap) is used to efficiently fetch the vertex with the smallest tentative distance. Distances Dictionary is initialized with infinity for all vertices except the source, which starts with a distance of 0. Relaxation Process checks each neighbor of the currently selected vertex, updating distances if a shorter path is found.