Facebook
From Flying Echidna, 5 Years ago, written in Python.
Embed
Download Paste or View Raw
Hits: 239
  1. def Dijkstra(graph, source):
  2.     starting_v = source - 1
  3.     vertices_list = graph.return_vertices_list()
  4.     unvisited = []
  5.     dist = [0] * len(vertices_list)
  6.     prev = [None] * len(vertices_list)
  7.  
  8.     def return_weight(graph, v1, v2):
  9.         edges_list = graph.return_neighbor_edges(v1)
  10.         edge = edges_list[edges_list[:, 1] == v2]
  11.         weight = edge[0][2]
  12.         return weight
  13.  
  14.     for vertice in vertices_list:
  15.         dist[vertice - 1] = float('inf')  
  16.         prev[vertice - 1] = 0
  17.         unvisited.append(vertice)
  18.  
  19.     dist[starting_v] = 0
  20.  
  21.     while unvisited:
  22.         minim = min(dist)
  23.         min_v_index = dist.index(minim)
  24.  
  25.         examined_v = unvisited[min_v_index]
  26.         del unvisited[min_v_index]
  27.  
  28.         neighbors_list = graph.return_neighbor_edges(examined_v)
  29.  
  30.         for neighbor in neighbors_list:
  31.             v_in = neighbor[1]
  32.             v_in_index = v_in - 1
  33.             alt = dist[min_v_index] + return_weight(graph, examined_v, v_in)
  34.  
  35.             if (alt < dist[v_in_index]):
  36.                 dist[v_in_index] = alt
  37.                 prev[v_in_index] = examined_v
  38.  
  39.     return dist, prev
  40.  
  41. distances, closest_n = Dijkstra(vers, 1)
  42.  
  43. print('Vertice:', [1, 2, 3, 4, 5])
  44. print('Closest:', closest_n)
  45. print('Weights:', distances)