Ejemplo n.º 1
0
def shortest_path(graph, sourceVertex):

    min_heap = PriorityQueue(True)
    distance = {}
    parent = {}

    for vertex in graph.all_vertex.values():
        min_heap.add_task(sys.maxsize, vertex)

    min_heap.change_task_priority(0, sourceVertex)
    distance[sourceVertex] = 0
    parent[sourceVertex] = None

    while min_heap.is_empty() is False:
        task = min_heap.peek_task()
        weight = min_heap.get_task_priority(task)               
        current =  min_heap.pop_task()
        distance[current] = weight

        for edge in current.edges:
            adjacent = get_other_vertex_for_edge(current, edge)
            if min_heap.contains_task(adjacent) is False:
                continue

            new_distance = distance[current] + edge.weight;
            if min_heap.get_task_priority(adjacent) > new_distance:
                min_heap.change_task_priority(new_distance, adjacent)
                parent[adjacent] = current
                

    return distance
Ejemplo n.º 2
0
def minimum_spanning_tree(graph):

    min_heap = PriorityQueue(True)
    vertex_to_edge = {}
    result = []

    for vertex in graph.all_vertex.values():
        min_heap.add_task(sys.maxsize, vertex)

    start_vertex = next(iter((graph.all_vertex.values())))
    min_heap.change_task_priority(0, start_vertex)
    while min_heap.is_empty() is False:
        current = min_heap.pop_task()

        if (current in vertex_to_edge):
            spanning_tree_edge = vertex_to_edge[current]
            result.append(spanning_tree_edge)

        for edge in current.edges:
            adjacent = get_other_vertex_for_edge(current, edge)
            if min_heap.contains_task(
                    adjacent) is True and min_heap.get_task_priority(
                        adjacent) > edge.weight:
                min_heap.change_task_priority(edge.weight, adjacent)
                vertex_to_edge[adjacent] = edge

    return result