Skip to content

Instantly share code, notes, and snippets.

@parkerziegler
Last active March 14, 2022 19:06
Show Gist options
  • Save parkerziegler/ca63a2b6c2fac215cef3f15604673151 to your computer and use it in GitHub Desktop.
Save parkerziegler/ca63a2b6c2fac215cef3f15604673151 to your computer and use it in GitHub Desktop.
A concise iterative version of depth-first search (DFS) in Python.
"""
Assume we have a graph modeled as a dictionary like so:
graph = {
'a': ['b', 'c'],
'b': ['d'],
'c': ['e'],
'd': ['f'],
'e': [],
'f': []
}
dfs will traverse this graph using depth-first search.
"""
def dfs(graph, source):
# Push current location to the stack.
stack = [source]
# While there are still nodes to be visited...
while len(stack) > 0:
# Pop the top node off the stack.
current = stack.pop()
print(current)
# Append every neighboring node to the stack.
for neighbor in graph[current]:
stack.append(neighbor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment