Advertisement
Eternoseeker

Ch-Assignment4-Djikstra

Nov 24th, 2023
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | Source Code | 0 0
  1. import heapq
  2.  
  3. class Graph:
  4.     def __init__(self, vertices):
  5.         self.V = vertices
  6.         self.graph = []
  7.         # It initializes the graph with the given number of vertices and an empty adjacency list.
  8.         for _ in range(vertices):
  9.             self.graph.append([])
  10.  
  11.     # This method allows you to add an edge between vertices u and v with a weight w to the graph's adjacency list
  12.     def add_edge(self, u, v, w):
  13.         self.graph[u].append((v, w))
  14.  
  15.     def dijkstra(self, src):
  16.         dist = [float('inf')] * self.V
  17.         dist[src] = 0
  18.         pq = [(0, src)]
  19.  
  20.         # Pop the vertex with the minimum distance from the priority queue.
  21.         # This ensures that the vertex with the shortest tentative distance is processed first. distance stores the distance, and u stores the vertex.
  22.         while pq:
  23.             distance, u = heapq.heappop(pq)
  24.            
  25.             # If the extracted distance is greater than the stored distance for vertex u in the dist array,
  26.             # skip this vertex and continue to the next one.
  27.             if distance > dist[u]:
  28.                 continue
  29.             for v, weight in self.graph[u]:
  30.                 if dist[u] + weight < dist[v]:
  31.                     dist[v] = dist[u] + weight
  32.                     heapq.heappush(pq, (dist[v], v))
  33.         return dist
  34.  
  35. # Input-driven code
  36. if __name__ == "__main__":
  37.     num_vertices = int(input("Enter the number of vertices: "))
  38.     g = Graph(num_vertices)
  39.  
  40.     num_edges = int(input("Enter the number of edges: "))
  41.     for _ in range(num_edges):
  42.         u, v, w = map(int, input("Enter source, destination, and weight separated by spaces: ").split())
  43.         g.add_edge(u, v, w)
  44.  
  45.     start_node = int(input("Enter the source node: "))
  46.     shortest_distances = g.dijkstra(start_node)
  47.  
  48.     print("Vertex \t Distance from Source")
  49.     for i in range(num_vertices):
  50.         print(i, "\t\t", shortest_distances[i])
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement