Last active
September 26, 2021 20:50
-
-
Save fabiosoft/30f5b92ce8f65610f375cbff9de7c0d7 to your computer and use it in GitHub Desktop.
Tree - Depth first search
This file contains 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
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