# sp.appendleft(pred[curr]) # curr = pred[curr] # else: # print(f'No path to {v}') # break # cycles are ignored # else: # sp.appendleft(source) # all_sp.append(list(sp)) # # return all_sp if __name__ == '__main__': dg = Digraph() # clrs example dg.add_weighted_edges_from([('t', 'x', 5), ('t', 'y', 8), ('t', 'z', -4), ('x', 't', -2), ('y', 'x', -3), ('y', 'z', 9), ('z', 'x', 7), ('z', 's', 2), ('s', 't', 6), ('s', 'y', 7)]) print(f'Graph: {dg}') print(f'Weights: {dg.weights}') print(bellman_ford(dg, 's')) print('') # dg = Digraph() # dg.add_edge('s', 'a', 3) # cormen book example # dg.add_edge('s', 'c', 5) # dg.add_edge('s', 'e', 2) # dg.add_edge('a', 'b', -4) # dg.add_edge('b', 'g', 4) # dg.add_edge('c', 'd', 6) # dg.add_edge('d', 'c', -3) # dg.add_edge('d', 'g', 8)
for v in g.neighbors(u): d = dist[u] + g.weight(u, v) if d < dist[v]: # relaxation dist[v] = d pred[v] = u heappush(minq, (dist[v], v)) # could have duplicate vertices in minq return pred, dist # to get the path, refer to the predecessors dictionary if __name__ == '__main__': dg = Digraph() # clrs example dg.add_weighted_edges_from([('s', 't', 10), ('s', 'y', 5), ('t', 'x', 1), ('t', 'y', 2), ('x', 'z', 4), ('y', 't', 3), ('y', 'x', 9), ('y', 'z', 2), ('z', 's', 7), ('z', 'x', 6)]) print(dg) print(dijkstra(dg, 's')) print('-----') dg = Digraph() # graph theory example youtube dg.add_weighted_edges_from([(0, 1, 4), (0, 2, 1), (1, 3, 1), (2, 1, 2), (2, 3, 5), (3, 4, 3)]) print(dg) print(dijkstra(dg, 0)) print('-----') # cp3 4.17 in https://visualgo.net/en/sssp dg = Digraph() dg.add_weighted_edges_from([(0, 1, 2), (0, 2, 6), (0, 3, 7), (1, 3, 3),
# dist[v] = sys.maxsize # pred[v] = None # dist[source] = 0 # # for v1 in sortedv: # for v2 in g.neighbors(v1): # if dist[v1] + g.weight(v1, v2) < dist[v2]: # relaxation # dist[v2] = dist[v1] + g.weight(v1, v2) # pred[v2] = v1 # # for v in g.vertices(): # generate all shortest paths # if v == source or pred[v] is None: # continue # sp = deque(v) # shortest path # curr = v # while pred[curr] != source: # sp.appendleft(pred[curr]) # curr = pred[curr] # sp.appendleft(source) # all_sp.append(list(sp)) # # return all_sp if __name__ == '__main__': dg = Digraph() # clrs example dg.add_weighted_edges_from([('r', 's', 5), ('r', 't', 3), ('s', 't', 2), ('s', 'x', 6), ('t', 'x', 7), ('t', 'y', 4), ('t', 'z', 2), ('x', 'y', -1), ('x', 'z', 1), ('y', 'z', -2)]) print(dag_sssp(dg, 's'))