u = min(non_visited_distance, key=non_visited_distance.get) visited[u] = True for vertex in neighbours(u): v = vertex[0] if visited[v] == False: if distance[v] > distance[u] + weight(u, v): distance[v] = distance[u] + weight(u, v) ancestor[v] = u return distance, ancestor if __name__ == "__main__": if len(sys.argv) != 2: print(f"Usage: python {sys.argv[0]} <graph-path>") os._exit(-1) read(sys.argv[1]) n_vertices = Graph.n_vertices print(f"Total vertices: {n_vertices}") # distance, ancestors =dijkstra(Graph,(1,'A')) distance, ancestors = dijkstra(Graph, (1)) # distance, ancestors =dijkstra(Graph,('A')) print(f"Distance: {distance}\nAncestors: {ancestors}") # Create output frontiers = {} for vertex in Graph.vertices: label = vertex[0] # check if distance key existis in output dist = distance[label] if not dist in frontiers:
dfs(neighbour, visited, sorted_vertices) sorted_vertices.insert(0, current) def topsort(): vertices = Graph.vertices visited: dict = {v: False for v in vertices} sorted_vertices = [] # first defined node is the first one to be visited for current in vertices: if not visited[current]: dfs(current, visited, sorted_vertices) return sorted_vertices if __name__ == "__main__": if len(sys.argv) != 2: print(f"Usage: python {sys.argv[0]} <graph-path>") os._exit(-1) read(sys.argv[1], directed=True) sorted_arr = topsort() sorted_arr.reverse() for index, v in enumerate(sorted_arr): print(v[1], end='') if index < len(sorted_arr) - 1: print(' -> ', end='') print('\n')