Skip to content

Instantly share code, notes, and snippets.

@mahmmoudkinawy
Created May 19, 2022 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahmmoudkinawy/1fc72746e967f01b4f3d0145d6ef56c7 to your computer and use it in GitHub Desktop.
Save mahmmoudkinawy/1fc72746e967f01b4f3d0145d6ef56c7 to your computer and use it in GitHub Desktop.
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