From a9108c69c470bf80549f3f16bad5e102a160a175 Mon Sep 17 00:00:00 2001 From: Anil Date: Wed, 4 Oct 2023 21:46:59 +0545 Subject: [PATCH] Added new python algorithm --- BFS_and_DFS_al.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 BFS_and_DFS_al.py diff --git a/BFS_and_DFS_al.py b/BFS_and_DFS_al.py new file mode 100644 index 0000000..15d78c6 --- /dev/null +++ b/BFS_and_DFS_al.py @@ -0,0 +1,47 @@ +# Normal BFS Traversal + +# model +model = {"S": ["A", "B", "C"], + "A": ["S", "D"], + "B": ["S", "E", "D", "G"], + "C": ["S", "E"], + "D": ["A", "F", "B"], + "F": ["D", "G", "E"], + "E": ["C", "F", "H", "B"], + "H": ["E", "G"], + "G": ["F", "B", "H"] + } + +initial = "S" +goal = "G" +frontier = [initial] +explored = [] + +count = 1 +while frontier: + value = frontier.pop(0) + if value not in explored: + explored.append(value) + if goal == value: + break + for val in model[value]: + if val not in explored and val not in frontier: + frontier.append(val) + count+=1 +print("BFS: ") +print(explored) + +# Normal DFS Traversal without Goal + +initial_dfs = "S" +frontier_dfs = [initial_dfs] +explored_dfs = [] +while frontier_dfs: + value = frontier_dfs.pop() + if value not in explored_dfs: + explored_dfs.append(value) + new_frontier_dfs = [val for val in model[value] + if val not in explored_dfs and val not in frontier_dfs][::-1] + frontier_dfs.extend(new_frontier_dfs) +print("DFS: ") +print(explored_dfs)