Exemple #1
0
    def bfs(self, rootId):
        """
        Execute a Breadth-First Search (BFS) in the graph starting from the
        specified node.
        :param rootId: the root node ID (integer).
        :return: the BFS list of nodes.
        """
        # if the root does not exists, return None
        if rootId not in self.nodes:
            return None

        # BFS nodes initialization
        bfs_nodes = []

        # queue initialization
        q = Queue()
        q.enqueue(rootId)

        explored = {rootId}  # nodes already explored

        while not q.isEmpty():  # while there are nodes to explore ...
            node = q.dequeue()  # get the node from the queue
            explored.add(node)  # mark the node as explored
            # add all adjacent unexplored nodes to the queue
            for adj_node in self.getAdj(node):
                if adj_node not in explored:
                    q.enqueue(adj_node)
            bfs_nodes.append(node)

        return bfs_nodes
def radixSort(listOfIntegers, k, b):
    """ Ordina interi da 1 a k usando bucket sort sulle cifre in base b
        Si ricorda che si fa uso della proprieta' di stabilita del bucketsort nelle varie iterazioni!
        O(n) se k=O(n^c) per c costante.
    """
    cifrek = int(math.ceil(math.log(k + 1, b)))
    if printSwitch.dumpOperations:
        print("radixSort(k={},b={}) cifrek={})".format(k, b, cifrek))

    for t in range(1, cifrek + 1):
        bucket = []
        for i in range(0, b):  # @UnusedVariable
            bucket.append(Queue())

        for j in range(0, len(listOfIntegers)):
            cifratj = listOfIntegers[j] % math.pow(
                b, t)  # leggiamo la t-esima cifra di A[j]
            cifratj = int(cifratj / math.pow(b, t - 1))
            bucket[cifratj].enqueue(
                listOfIntegers[j]
            )  # aggiungiamo listOfIntegers[j] nel bucket corretto

        j = 0
        for e in bucket:
            while not e.isEmpty():
                listOfIntegers[j] = e.dequeue()
                j += 1
        if printSwitch.dumpOperations:
            print(listOfIntegers)
 def BFS(self):
     """
     Permette di restituire una lista di elementi ottenuta da una visita
     in ampiezza dell'albero.
     :return: lista nodi
     """
     res = []
     q = Queue()
     if self.root is not None:
         q.enqueue(self.root)
     while not q.isEmpty():
         current = q.dequeue()
         res.append(current.info)
         for s in current.sons:
             q.enqueue(s)
     return res