Exemplo n.º 1
0
    def visitaInPriorita(self):
        """
        Visita che parte da dal vertice di costo massimo ed usa
        una coda con priorità come frangia F
        :return: lista con ordine della visita.
        """
        assert not self.isEmpty(), "Il grafo è vuoto"

        nodeMaxPriority = self.getNodes()[0]

        for node in self.getNodes():                #troviamo il nodo di costo maggiore
            if node.weight > nodeMaxPriority.weight:
                nodeMaxPriority = node

        F = PriorityQueue(self.qtype).queue         #inizializzazione della frangia
        assert F is not None, "Tipo coda non valida"
        """
        Tweak per l'inserimento del peso in una Coda con Priorità:
        l'implementazione delle code presente nelle Librerie mantiene in alto il minimo valore
        disponibile, mentre il testo del progetto rchiede che la nostra coda mantenga in alto
        la massima priorità. Per ovviare al problema si inseriscono come chiavi dei nodeId i
        pesi con segno negativo.
        """

        F.insert(nodeMaxPriority, -nodeMaxPriority.weight)      #inizializziamo F con il nodo di costo maggiore (nodo, peso)
        visited_nodes = []
        explored_nodes = set()

        while not F.isEmpty():  # while there are nodes to explore ...
            node = F.findMin()   # findMin() ritorna l'id del nodo con priorità massima
            F.deleteMin()
            explored_nodes |= {node.id}
            visited_nodes.append(node)
            # add all adjacent unexplored nodes to the stack
            if len(F.heap) + len(visited_nodes) < self.numNodes():
                for adj_nodeId in self.getAdj(node.id):
                    if adj_nodeId not in explored_nodes:
                        F.insert(self.getNode(adj_nodeId), -self.getNode(adj_nodeId).weight)
        return visited_nodes
    def dijkstra(self, labelStart: str, labelEnd: str):
        startVertex: Vertex = self.findVertexByLabel(labelStart)
        startVertex.weight = 0
        pq = PriorityQueue()
        for vertex in self.vertices:
            pq.insert(vertex)
        while not pq.isEmpty():
            min: Vertex = pq.deleteMin()
            for neighbour in self.adjacencyList[min.label]:
                # loop through self.vertices avoided, O(1) instead of O(V)
                # tmp: Vertex = self.findVertexByLabel(neighbour.label)
                tmp: Vertex = self.vertices[neighbour.index]
                if min.weight + neighbour.weight < tmp.weight:
                    self.prev[neighbour.label] = min.label
                    tmp.weight = min.weight + neighbour.weight
                    pq.decreaseKey(tmp.key)

        print(self.showPath(labelEnd))
Exemplo n.º 3
0
    def prim(self, labelStart: str):
        result: str = ""
        startVertex: Vertex = self.findVertexByLabel(labelStart)
        startVertex.weight = 0
        pq = PriorityQueue()
        for vertex in self.vertices:
            pq.insert(vertex)
        while not pq.isEmpty():
            min: Vertex = pq.deleteMin()
            if self.prev[min.label] is not None:
                result += self.prev[min.label] + " -> " + min.label + ", "
            for neighbour in self.adjacencyList[min.label]:
                # loop through self.vertices avoided, O(1) instead of O(V)
                # tmp: Vertex = self.findVertexByLabel(neighbour.label)
                tmp: Vertex = self.vertices[neighbour.index]
                if neighbour.weight < tmp.weight:
                    self.prev[neighbour.label] = min.label
                    tmp.weight = neighbour.weight
                    pq.decreaseKey(tmp.key)

        print(result)