Last active
March 14, 2022 19:06
-
-
Save parkerziegler/ca63a2b6c2fac215cef3f15604673151 to your computer and use it in GitHub Desktop.
A concise iterative version of depth-first search (DFS) in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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