Si encuentras alguna incompatibilidad con tu código o trabajo, recuerda probar siempre en un ambiente de testing antes aplicar el código al trabajo final.
Ejemplo 1: primera búsqueda en profundidad de Python
#leftto right, pre-order depth first tree search, iterative.O(n) time/space
def depthFirstSearch(root):
st =[root]while st:
current = st.pop()print(current)if current.right is not None: st.append(current.right)if current.left is not None: st.append(current.left)
Ejemplo 2: dfs python
###############
#The Algorithm(In English):
# 1) Pick any node.
# 2) If it is unvisited, mark it as visited and recur on all its
#adjacentnodes.
# 3) Repeat until all the nodes are visited,or the node to be
#searchedis found.#The graph below(declared as a Python dictionary)#isfrom the linked website and is used for the sake of#testingthe algorithm. Obviously, you will have your own#graphto iterate through.
graph ='A':['B','C'],'B':['D','E'],'C':['F'],'D':[],'E':['F'],'F':[]
visited =set() # Set to keep track of visited nodes.
##################
#The Algorithm(In Code)
def dfs(visited, graph, node):if node not in visited:print(node)
visited.add(node)for neighbour in graph[node]:dfs(visited, graph, neighbour)#Driver Code to test in python yourself.#Note that when calling this, you need to#callthe starting node. In thiscase it is 'A'.dfs(visited, graph,'A')#NOTE: There are a few ways to do DFS, depending on what your#variablesare and/or what you want returned. This specific#exampleis the most fleshed-out, yet still understandable,#explanationI could find.
Ejemplo 3: primera búsqueda en profundidad de Python
#leftto right, pre-order depth first tree search, recursive.O(n) time/space
def depthFirstSearchRec(root):if root == None:returnprint(root)depthFirstSearch(root.left)depthFirstSearch(root.right)
Sección de Reseñas y Valoraciones
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)