Exemplo n.º 1
0
def dijkstra(graph, source):
	'''Apply the Dijkstra algorithm and return the a list where
	each position represents a vertice and its content represents 
	the predecessor'''

	vertices = [] #list of vertices
	Q = PriorityQueue() #priority queue

	#fills 'vertices' and 'Q', each vertex receive the distance iquals infinity
	for v in range(len(graph)):
		vertices.append(Vertex(v)) 
		Q.add_with_priority(v, vertices[v].dist)

	#the source vertex receive the distance zero
	vertices[source] = Vertex(num=source, dist=0)
	Q.decrease_priority(source, 0)

	while len(Q) != 0:
		u = Q.extract_min()

		for neighbor in get_adjacent(graph, u.num):
			alt = graph[u.num][neighbor] + u.dist
			Alt = Vertex(neighbor, alt)

			if vertices[neighbor].greater_than(Alt):
				vertices[neighbor].dist = alt
				vertices[neighbor].prev = u.num
				Q.decrease_priority(neighbor, alt)

	return [v.prev for v in vertices]
Exemplo n.º 2
0
def prim(G, r=0):
    keys = {}
    parents = {}
    adj_matrix = G.get_adj_matrix()

    for i in range(G.get_len()):
        keys[i] = INFINITY
        parents[i] = None

    keys[r] = 0

    array = [[keys[v], v] for v in range(G.get_len())]
    Q = PriorityQueue(array)

    while not Q.is_empty():
        u = Q.extract_min()  # u = array di 2 valori [chiave, nodo]

        for v in range(
                G.get_len()):  # per ogni nodo nella lista delle adiacenze di u
            # se u è in Q e il valore del nodo è minore di quello della chiave corrente e non è un cappio (elemento
            # della diagonale)
            if Q.is_there_element(
                    v) and adj_matrix[u[1]][v] < keys[v] and u != v:
                old_val = keys[
                    v]  # salvo il vecchio valore (serve per decrease_key)
                keys[v] = adj_matrix[u[1]][v]  # aggiorno il nuovo valore
                parents[v] = u[1]  # modifico il genitore del nodo
                Q.decrease_key(
                    v, old_val, keys[v]
                )  # decrem valore nell'albero per poi estrarre il minimo al prox giro

    return get_prim_result(G, [(v, parents[v])
                               for v in range(G.get_len()) if v != r])
Exemplo n.º 3
0
def get_MST(connections, n):
    if n <= 1:
        return []

    graph = defaultdict(set)
    pq = PriorityQueue()
    INT_MAX = 2**32 - 1
    map = dict()
    result = []

    for u, v, w in connections:
        graph[u].add((v, w))
        graph[v].add((u, w))
        if not pq.find(u):
            pq.insert(u, INT_MAX)
        if not pq.find(v):
            pq.insert(v, INT_MAX)

    pq.update_priority(connections[0][0], 0)

    while pq.size() > 0:
        curr_node = pq.extract_min()
        if curr_node in map:
            result.append(map[curr_node])
            del map[curr_node]

        for nhbr in graph[curr_node]:
            node = nhbr[0]
            if pq.find(node):
                if pq.get_priority(node) > nhbr[1]:
                    pq.update_priority(node, nhbr[1])
                    map[node] = [curr_node, node]

    if len(result) == n - 1:
        return result
    else:
        return -1