Skip to content

Instantly share code, notes, and snippets.

@parkerziegler
Created March 14, 2022 19:04
Show Gist options
  • Save parkerziegler/98d79891d8898dff0ff6083ea7f9f87c to your computer and use it in GitHub Desktop.
Save parkerziegler/98d79891d8898dff0ff6083ea7f9f87c to your computer and use it in GitHub Desktop.
A concise recursive 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_rec will traverse this graph using depth-first search.
"""
def dfs_rec(graph, source):
print(source)
for neighbor in graph[source]:
dfs_rec(graph, neighbor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment