Skip to content

Instantly share code, notes, and snippets.

@fabiosoft
Last active September 26, 2021 20:50
Show Gist options
  • Save fabiosoft/30f5b92ce8f65610f375cbff9de7c0d7 to your computer and use it in GitHub Desktop.
Save fabiosoft/30f5b92ce8f65610f375cbff9de7c0d7 to your computer and use it in GitHub Desktop.
Tree - Depth first search
def recursive_dfs(graph, source,path = []):
if source not in path:
path.append(source)
if source not in graph:
# leaf node, backtrack
return path
for neighbour in graph[source]:
path = recursive_dfs(graph, neighbour, path)
return path
# Adjacency List graph
graph = {"A":["B","C", "D"],
"B":["E"],
"C":["F","G"],
"D":["H"],
"E":["I"],
"F":["J"]}
path = recursive_dfs(graph, "A")
print(" ".join(path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment