Guest User

Untitled

a guest
Jan 23rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. graph = {'s': {'v':1,'w':4 },
  2. 'v': {'w':2,'t':6},
  3. 'w': {'t':3},
  4. 't': {'': None}
  5. }
  6. def dj(graph, start):
  7. Q = []# queue to hold all the vertices
  8. dist = {} #dictionary to hold all the distance
  9. prev = {} #dictionary to hold all the previous node visited
  10.  
  11. for key in graph.keys():
  12. dist[key] = 1000
  13. prev[key] = ""
  14. Q.append(key)
  15.  
  16.  
  17. dist[start] = 0
  18.  
  19. #I had to have another distance data structure dst
  20. # to store all the distance covered
  21. # I am not fond of it
  22. dst = []
  23.  
  24. while Q:
  25. u = min(dist, key = dist.get)#Here I get the minimum distance
  26. Q.remove(u)#remove the min one from Q
  27. for v in graph[u]:
  28. #I also want to improvise this condition block
  29. #It is because of 't': {'': None}
  30. if graph[u][v] is None:
  31. continue
  32. alt = dist[u] + graph[u][v]
  33. if alt < dist[v]:
  34. dist[v] = alt
  35. prev[v] = u
  36. d = (dist.pop(u))
  37. dst.append(d)
  38.  
  39. return dst,prev
  40.  
  41. print(dj(graph,'s'))
Add Comment
Please, Sign In to add comment