Created
May 19, 2022 15:33
-
-
Save mahmmoudkinawy/1fc72746e967f01b4f3d0145d6ef56c7 to your computer and use it in GitHub Desktop.
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
graph = { | |
'S': ['A', 'B', 'D'], | |
'A': ['C'], | |
'B': ['D'], | |
'C': ['D', 'G'], | |
'D': ['G'], | |
# 'G': [] # we can write/ignore this (both are OK) | |
} | |
def dfs(graph, start, goal): | |
visited = [] | |
stack = [[start]] | |
while stack: | |
path = stack.pop() | |
node = path[-1] | |
if node in visited: | |
continue | |
visited.append(node) | |
if node == goal: | |
return path | |
else: | |
adjacent_nodes = graph.get(node, []) | |
for node2 in adjacent_nodes: | |
new_path = path.copy() | |
new_path.append(node2) | |
stack.append(new_path) | |
solution = dfs(graph, 'S', 'G') | |
print('Solution is', solution) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment