Esempio n. 1
0
def prim(graph, start_node):
    queue = PriorityQueue()
    parent = {}
    mst = []
    mst_sum = 0

    for node in graph.get_nodes():
        queue.add_task(task=node, priority=float('Inf'))
        parent[node] = None

    # put first node in the queue
    queue.add_task(task=start_node, priority=0)

    while queue.not_empty():
        cheapest_node = queue.pop_task()
        if parent[cheapest_node] is not None:
            temp_weight = float(graph.get_default_weights((cheapest_node, parent[cheapest_node]))[0])
            mst.append((temp_weight, (cheapest_node, parent[cheapest_node])))
            mst_sum += temp_weight
        for adj_node in graph.get_node_neighbours(cheapest_node):
            edge_weight = float(graph.get_default_weights((cheapest_node, adj_node))[0])
            if queue.contains_task(adj_node) and edge_weight < queue.get_priority(adj_node):
                parent[adj_node] = cheapest_node
                queue.add_task(task=adj_node, priority=edge_weight)

    print "Prim Weight: ", mst_sum
    return mst
Esempio n. 2
0
def dijkstra(graph, start, end=None):
    nodes = graph.get_nodes()
    # initialize distance dictionary

    dist = {node: float('Inf') for node in nodes}
    dist[start] = 0
    # initialize predecessor dictionary
    pred = {node: None for node in nodes}

    # initialize prio queue for "unvisited nodes
    nodes_nonfinal = PriorityQueue()
    for node in nodes:
        nodes_nonfinal.add_task(task=node, priority=dist[node])

    # main computation loop
    while nodes_nonfinal.not_empty():
        u = nodes_nonfinal.pop_task()
        for adj in graph.get_node_neighbours(u):
            if nodes_nonfinal.contains_task(adj):
                temp = dist[u] + float(graph.get_default_weights((u, adj))[0])
                if temp < dist[adj]:

                    pred[adj] = u
                    nodes_nonfinal.add_task(task=adj, priority=temp)

    # if an end node was specified, the corresponding shortest path shall be
    # computed and displayed
    if end is not None:
        path, path_sum = shortest_path(graph, pred, end)
        #print '#' * 50
        #print 'Path: ', path
        #print 'Weight: ', path_sum
        return path
    else:
        get_shortest_path_tree(graph, pred, start)