Advertisement
halaluddin

Dijkstra_Correct_Solution

Nov 23rd, 2019
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. from heapq import heappop, heappush, heapify
  2. from sys import maxsize
  3.  
  4.  
  5. class Graph:
  6.     def __init__(self, vertices):
  7.         self.v = vertices+1
  8.         self.cost = [[0]*(vertices+1) for _ in range(vertices+1)]
  9.  
  10.     def add_edges(self, src, dest, weight):
  11.         if self.cost[src][dest] and self.cost[dest][src]:
  12.             if self.cost[src][dest] > weight and self.cost[dest][src] > weight:
  13.                 self.cost[src][dest] = weight
  14.                 self.cost[dest][src] = weight
  15.         else:
  16.             self.cost[src][dest] = weight
  17.             # Becouse, Given Graph is undirected.
  18.             self.cost[dest][src] = weight
  19.  
  20.     def dijkstra(self, source):
  21.        
  22.         Q = [(0, source)]
  23.         distance = [maxsize] * self.v
  24.         distance[source] = 0
  25.         heapify(Q)
  26.  
  27.         while Q:
  28.  
  29.             node_with_min_dist = heappop(Q)
  30.             u = node_with_min_dist[1]
  31.  
  32.             for v in range(self.v):
  33.                 if self.cost[u][v] and distance[u] + self.cost[u][v] < distance[v]:
  34.                     distance[v] = distance[u] + self.cost[u][v]
  35.                     heappush(Q, (distance[v], v))
  36.                
  37.         return distance[1:]
  38.  
  39.  
  40.  
  41. def shortestReach(n, m):
  42.    
  43.     g = Graph(n)
  44.     for _ in range(m):
  45.         s, d, w = list(map(int, input().split()))
  46.         g.add_edges(s, d, w)
  47.    
  48.     shortest_distance = g.dijkstra(int(input()))
  49.  
  50.     return shortest_distance
  51.    
  52.  
  53.  
  54. if __name__ == '__main__':
  55.  
  56.     t = int(input())
  57.  
  58.     for t_itr in range(t):
  59.         nm = input().split()
  60.  
  61.         n = int(nm[0])
  62.  
  63.         m = int(nm[1])
  64.  
  65.         result = shortestReach(n, m)
  66.  
  67.         for i in result:
  68.             if i == 0: continue
  69.             elif i == maxsize: print(-1, end=' ')
  70.             else: print(i, end=' ')
  71.         print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement