Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

iterative dfs python

G = {
    'A': {'C'},
    'B': {'A'},
    'C': {'B', 'D', 'E'},
    'D': {},
    'E': {}
}

def getNeighbors(vertex):
    return list(G[vertex])

# iterative dfs in Python
def dfs(root, target):
    stk = [] # stack (LIFO)
    visited = set() # keep track of vertices we've seen before
    stk.insert(0, root) # push root to top of stack
    visited.add(root) # mark root (start point) as visited
    while len(stk): # while our stk is not empty
        top = stk.pop(0)
        if top == target: # is top of stk our target?
            return True # we found a path from root to target in our graph!
        for neighbor in getNeighbors(top): # you must write a 'getNeighbor' function
            # this function should return all the vertices connected to root
            if neighbor in visited: continue # don't revisit vertices!
            visited.add(neighbor) # mark neighbor as visited
            stk.insert(0, neighbor) # add neighbor to our stack
    
    return False # we went through every path from 'root' and didn't find 'target'

result = dfs('C', 'E')
print(result)
Comment

PREVIOUS NEXT
Code Example
Python :: np.zeros((3,3)) 
Python :: midpoint 
Python :: print flush python 
Python :: python sort multiple lists based on sorting of single list 
Python :: numpy randint 
Python :: strp datetime 
Python :: max in a list python 
Python :: how to use fastapi ApiClient with pytest 
Python :: kruskal python implementation 
Python :: is python oop 
Python :: python read scv 
Python :: pygame get keypress code 
Python :: how to install pyinstaller 
Python :: create qr code in python 
Python :: python invert an array 
Python :: print font size python 
Python :: how to create a variablein python 
Python :: getters and setters in python 
Python :: python run in another thread decorator 
Python :: list exclude list 
Python :: how to take input for list in one line in python 
Python :: python text input 
Python :: python global variable across files 
Python :: jupyter notebook show full dataframe cell 
Python :: python integer to string 
Python :: create 8ball command in discord.py 
Python :: if number is divisible by 3 python 
Python :: file manage py line 17 from exc django 
Python :: how to print keys and values of dictionary together in python? 
Python :: delete element list python 
ADD CONTENT
Topic
Content
Source link
Name
7+8 =