Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. distances = {
  2.     'A': {'B': 5},
  3.     'B': {'C': 10},
  4.     'C': { 'D': 50, 'F': 1},
  5.     'D': {},
  6.     'F': {'B': 2},
  7. }
  8.  
  9.  
  10. def dixstra(graph,start,end):
  11.     unvisited ={ i: float("inf") for i in graph}
  12.     visited = dict()
  13.     node= start
  14.     unvisited[node] = 0
  15.     while True:
  16.         for neighbour, distance in graph[node].items():
  17.             if neighbour not in unvisited: continue
  18.             new_distance = distance + unvisited[node]
  19.             if unvisited[neighbour] > new_distance:
  20.                 unvisited[neighbour] = new_distance
  21.         visited[node]= unvisited[node]
  22.         if node == end: break
  23.         del unvisited[node]
  24.         if not unvisited: break
  25.         node = next_node(unvisited)
  26.     return visited
  27.  
  28.  
  29. def next_node(costs):
  30.     lowest_cost = float('inf')
  31.     lowest_cost_node = None
  32.     for node in costs:
  33.         if costs[node] < lowest_cost :
  34.             lowest_cost = costs[node]
  35.             lowest_cost_node= node
  36.  
  37.     return lowest_cost_node
  38.  
  39.  
  40. print(dixstra(distances,"A","D"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement