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

        # DFS nodes initialization
        dfs_nodes = []

        # queue initialization
        s = Stack()
        s.push(rootId)

        explored = {rootId}  # nodes already explored

        while not s.isEmpty():  # while there are nodes to explore ...
            node = s.pop()  # get the node from the stack
            explored.add(node)  # mark the node as explored
            # add all adjacent unexplored nodes to the stack
            for i in range(len(self.getAdj(node)) - 1, -1, -1):
                adj_node = self.getAdj(node)[i]
                if adj_node not in explored:
                    explored.add(adj_node)
                    s.push(adj_node)
            dfs_nodes.append(node)

        return dfs_nodes
예제 #2
0
def hasCycleDFS(G):
    for rootId in G.getNodes():

        dfs_nodes = []  # qui è dove metteremo i Nodi Chiusi

        # Inizializziamo la pila dove inseriamo i Nodi Aperti
        s = Stack()
        s.push(rootId.id)

        explored = {rootId.id}  # nodi visitati

        while not s.isEmpty():  # finchè ci sono nodi da esplorare ...
            node = s.pop()  # prendiamo il nodo dalla pila
            explored.add(node)  # marchiamo il nodo
            # aggiungiamo tutti i nodi adiacenti non esplorati nella pila
            for i in range(len(G.getAdj(node)) - 1, -1, -1):
                adj_node = G.getAdj(node)[i]
                if adj_node not in explored:
                    explored.add(adj_node)
                    s.push(adj_node)
                elif s.inPila(
                        adj_node
                ):  # se il nodo adiacente è un nodo aperto allora abbiamo un ciclo!
                    return 1
            dfs_nodes.append(node)
        return 0
예제 #3
0
def hasCycleDFSIter(G):
    """
    Esegue una visita DFS nel grafo G a partire dal primo nodo. Se un nodo non ancora visitato si trova già
    nello stack, allora ai passi successivi si genererà un arco all'indietro, ovvero un arco da un nodo ad uno già
    visitato. È importante notare che per ogni nodo non viene preso in considerazione l'arco diretto verso il padre,
    poiché quest'ultimo è già marcato come visitato.
    :param G: Graph.
    :return: bool.
    """
    # rootId = random.choice(list(G.nodes.keys()))  # inizia la visita da un nodo random
    rootId = list(G.nodes.keys())[0]

    # DFS nodes initialization
    dfsNodes = set()

    # queue initialization
    s = Stack()
    s.push(rootId)

    explored = {rootId}  # nodes already explored

    while not s.isEmpty():  # while there are nodes to explore ...
        node = s.pop()  # get the node from the stack
        explored.add(node)  # mark the node as explored
        # add all adjacent unexplored nodes to the stack
        for adjNode in G.getAdj(node):
            if adjNode not in explored:
                s.push(adjNode)
        if node in dfsNodes:
            return True
        dfsNodes.add(node)

    return False
예제 #4
0
 def DFS(self):
     """
     Permette di restituire una lista di elementi ottenuta da una visita
     in profondità dell'albero.
     :return: list nodi
     """
     res = []
     stack = Pila()
     if self.root is not None:
         stack.push(self.root)
     while not stack.isEmpty():
         current = stack.pop()
         res.append(current.info)
         for i in range(len(current.sons) - 1, -1, -1):
             stack.push(current.sons[i])
     return res
 def foundNodeByElem(self, elem):
     """
     Visita DFS per cercare un nodo che contenga l'indice richiesto.
     :param elem: da cercare
     :return: nodo
     """
     stack = Pila()
     if self.root is not None:
         stack.push(self.root)
     while not stack.isEmpty():
         current = stack.pop()
         if elem == current.info:
             return current
         for i in range(len(current.sons)):
             stack.push(current.sons[i])
     return None
    def print(self):
        """
        Permette di stampare l'albero. Per farlo si usa una pila di appoggio
        """
        stack = Pila()
        if self.root is not None:
            stack.push(
                [self.root, 0]
            )  # pila di liste di due elementi [il nodo, il livello occupato dal nodo]
            print("-- Tree --")
        else:
            print("Empty tree!")
            return
        while not stack.isEmpty():
            current = stack.pop()
            level = current[1]
            print("|---" * level + str(current[0].info))
            for son in current[0].sons:
                stack.push([son, level + 1])

        print("-- Tree End -- ")
예제 #7
0
파일: Graph.py 프로젝트: stewieGIT/Progetto
    def dfs(self, rootId, dimens):
        """
        Execute a Depth-First Search (DFS) in the graph starting from the
        specified node.
        :param rootId: the root node ID (integer).
        :return: the DFS list of nodes.
        """
        # if the root does not exists, return None
        if rootId not in self.nodes:
            return None

        # DFS nodes initialization
        dfs_nodes = []

        # queue initialization
        s = Stack()
        s.push(rootId)

        explored = {rootId}  # nodes already explored

        while not s.isEmpty():  # while there are nodes to explore ...
            node = s.pop()  # get the node from the stack
            explored.add(node)  # mark the node as explored
            # add all adjacent unexplored nodes to the stack
            for adj_node in self.getAdj(node):
                if adj_node not in explored:
                    s.push(adj_node)
            dfs_nodes.append(node)

            # viene aggiunto un semplice controllo,se nella dfs si passa per un nodo piu volte
            # allora ce' un ciclo e si ritorna true

            if dfs_nodes.count(node)>1:
                print("Cycle detected!")
                return True
        # se il while termina il ciclo non cè e si ritorna false

        print("NOT cycle.")
        return False
예제 #8
0
 def __subtreeNodesNumber(self, node):
     """
     :param node: radice del sottoalbero
     :return: numero di nodi del sottoalbero radicato in node
     """
     res = []
     stack = Pila()
     if node is not None:
         stack.push(node)
     while not stack.isEmpty():
         current = stack.pop()
         res.append(current.info)
         if current.rightSon is not None:
             stack.push(current.rightSon)
         if current.leftSon is not None:
             stack.push(current.leftSon)
     return len(res)
예제 #9
0
 def DFS(self):
     """
     Permette di restituire una lista di elementi ottenuta da una visita
     in profondità dell'albero.
     :return: list nodi
     """
     res = []
     stack = Pila()
     if self.root is not None:
         stack.push(self.root)
     while not stack.isEmpty():
         current = stack.pop()
         res.append(current.info)
         if current.rightSon is not None:
             stack.push(current.rightSon)
         if current.leftSon is not None:
             stack.push(current.leftSon)
     return res
def iterativeQuickSort(l, left, right, det=False):
    theStack = Stack()
    theStack.push(left)
    theStack.push(right)
    while not theStack.isEmpty():
        right = theStack.pop()
        left = theStack.pop()

        if printSwitch.dumpOperations:
            print("quickSortIter-step({},{})".format(left, right))

        if right <= left:
            continue

        mid = partition(l, left, right, det)

        theStack.push(left)
        theStack.push(mid - 1)

        theStack.push(mid + 1)
        theStack.push(right)
예제 #11
0
def iterativeQuickSort(l, left, right, selectionAlgorithm, *otherParameters):
    theStack = Stack()
    theStack.push(left)
    theStack.push(right)
    while not theStack.isEmpty():
        right = theStack.pop()
        left = theStack.pop()

        if printSwitch.dumpOperations:
            print("quickSortIter-step({},{},{})".format(
                left, right, selectionAlgorithm.__name__))

        if right <= left:
            continue

        k = ceil(len(l[left:right + 1]) / 2)
        median = selectionAlgorithm(l[left:right + 1], k, *otherParameters)

        mid = partitionDet(l, left, right, median)

        theStack.push(left)
        theStack.push(mid - 1)

        theStack.push(mid + 1)
        theStack.push(right)