Skip to content

Instantly share code, notes, and snippets.

@sonnyksimon
Last active July 6, 2020 16:55
Show Gist options
  • Save sonnyksimon/8d4d610a9cbeb3cf35a9f61f624cac53 to your computer and use it in GitHub Desktop.
Save sonnyksimon/8d4d610a9cbeb3cf35a9f61f624cac53 to your computer and use it in GitHub Desktop.
depth-first search in Python
# Using a dictionary to act as an adjacency list
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
# visited: Set to keep track of visited nodes.
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
def iterative_dfs(visited, graph, node):
stack = [node]
while stack:
node = stack.pop()
if node not in visited:
print (node)
visited.add(node)
for neighbour in reversed(graph[node]):
stack.append(neighbour)
# Driver Code
dfs(set(), graph, 'A')
iterative_dfs(set(), graph, 'A')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment