Wednesday, October 13, 2021

dfs not binary tree \\python

 https://steven-chen.medium.com/python-graph-search-dfs-bfs-and-tree-traversal-preorder-inorder-postorder-88be4b1df0f9

https://www.educative.io/edpresso/how-to-implement-depth-first-search-in-python


https://stackabuse.com/depth-first-search-dfs-in-python-theory-and-implementation/


from typing import Dict, List, Any, Union
graph: Dict[Any, Union[List[str], List[Any]]] = dict(
S=['A', 'B', 'C'],
A=['D', 'E', 'G'],
B=['G'], D=[], E=[], G=[], C=['G'])
def dfs(graph, start, target, path, visited = set()):
path.append(start)
visited.add(start)
if start == target:
return path
for neighbour in graph[start]:
if neighbour not in visited:
result = dfs(graph, neighbour, target, path, visited)
if result is not None:
return result
return None
traversal_path = []
traversal_path = dfs(graph, 'S', 'G', traversal_path)
print(traversal_path)

No comments:

Post a Comment