Example #1
0
def bellman_ford(g, w, s):
    graph.init_single_source(g, s)
    for i in range(1, len(g.vertices)):
        for u,v in g.edges:
            graph.relax(g.vertices[u], g.vertices[v], w)
    for u,v in g.edges:
        if g.vertices[v].d > g.vertices[u].d + w[(u,v)]:
            return False
    return True
Example #2
0
def dijkstra(graph, weights, start_vertex):
    graph_utils.init_single_source(graph, start_vertex)
    queue = [vertex for vertex in graph.vertices.values()] # vertices to process
    heapq.heapify(queue)
    s = [] # set of vertices with shortest path already determined
    while queue:
        u = heapq.heappop(queue) # extract min
        s.append(u)
        for v in u.edges:
            graph_utils.relax(u, v, weights)
Example #3
0
def dijkstra(graph, weights, start_vertex):
    graph_utils.init_single_source(graph, start_vertex)
    queue = [vertex
             for vertex in graph.vertices.values()]  # vertices to process
    heapq.heapify(queue)
    s = []  # set of vertices with shortest path already determined
    while queue:
        u = heapq.heappop(queue)  # extract min
        s.append(u)
        for v in u.edges:
            graph_utils.relax(u, v, weights)
Example #4
0
def dijkstra(graph, costs, start_vertex):
    current_node = graph.vertices[start_vertex.key]
    graph_utils.init_single_source(graph, current_node)
    unvisited = set(graph.vertices[vertex] for vertex in graph.vertices)
    while current_node:
        neighbors = [vertex for vertex in current_node.edges
                     if vertex in unvisited]
        for neighbor in neighbors:
            if (current_node.d + costs[(current_node.key, neighbor.key)]) < neighbor.d:
                neighbor.d = current_node.d + costs[(current_node.key, neighbor.key)]
        unvisited.remove(current_node)
        if not unvisited:
            break
        min_node = min(unvisited, key=lambda x: x.d)
        current_node = min_node if min_node.d != float('inf')  and min_node in unvisited else None
Example #5
0
def dijkstra_2(graph, costs, start_vertex):
    current_node = graph.vertices[start_vertex.key]
    graph_utils.init_single_source(graph, current_node)
    unvisited = set(graph.vertices[vertex] for vertex in graph.vertices)
    while current_node:
        neighbors = [
            vertex for vertex in current_node.edges if vertex in unvisited
        ]
        for neighbor in neighbors:
            if (current_node.d +
                    costs[(current_node.key, neighbor.key)]) < neighbor.d:
                neighbor.d = current_node.d + costs[(current_node.key,
                                                     neighbor.key)]
        unvisited.remove(current_node)
        if not unvisited:
            break
        min_node = min(unvisited, key=lambda x: x.d)
        current_node = min_node if min_node.d != float(
            'inf') and min_node in unvisited else None