From dadbf591c3f7a10656d1cb5ebb3a166e4e9277d9 Mon Sep 17 00:00:00 2001 From: Shubham Maurya <114727104+Shubhamprogrammar@users.noreply.github.com> Date: Thu, 31 Oct 2024 17:50:39 +0530 Subject: [PATCH] Add files via upload --- bfs.py | 29 ++++++++++++++++++++++++++++ dfs.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 bfs.py create mode 100644 dfs.py diff --git a/bfs.py b/bfs.py new file mode 100644 index 000000000..f26554b84 --- /dev/null +++ b/bfs.py @@ -0,0 +1,29 @@ +class first: + def __init__(self,graph,start,goal): + self.start = start + self.graph = graph + self.goal=goal + + def bfs_shortest_path(self): + explored=[] + queue = [[self.start]] + if self.start==self.goal: + return "That was easy! start=goal" + while queue: + path = queue.pop() + node = path[-1] + if node not in explored: + neighbors = self.graph[node] + for neighbor in neighbors: + new_path = list(path) + new_path.append(neighbor) + queue.append(new_path) + if neighbor == self.goal: + return new_path + explored.append(node) + return "So sorry, but a connecting path does not exist" + +graph = {'A':['Z','S','T'],'B':['U','P','G','F'],'C':['D','R','P'],'D':['M'],'E':['H'],'I':['V','N'],'L':['T','M'],'O':['Z','S'],'P':['R'],'U':['V'],'Z':['O','A'],'S':['O','A','R','F'],'T':['A','L'],'M':['L','D'],'R':['S','P','C'],'F':['S','B']} +f = first(graph,'A','B') +print(f.bfs_shortest_path()) + \ No newline at end of file diff --git a/dfs.py b/dfs.py new file mode 100644 index 000000000..8bd1a37d0 --- /dev/null +++ b/dfs.py @@ -0,0 +1,61 @@ +graph = {'Arad': ['Zerind', 'Sibiu', 'Timisoara'], + +'Bucharest': ['Urziceni', 'Pitesti', 'Giurgiu', 'Fagaras'], + +'Craiova': ['Dobreta', 'Bimnicu Vilcea', 'Pitesti'], + +'Dobreta': ['Mehadia'], + +'Eforie': ['Hirsoya'], + +'Tasai': ['Vaslui', 'Neamt'], + +'Lugoj': ['Timisoara', 'Mehadia'], + +'Oradea': ['Zerind', 'Sibiu'], + +'Pitesti': ['Bimnicu Vilcea'], + +'Urziceni': ['Vaslui'], + +'Zerind': ['Oradea', 'Arad'], + +'Sibiu': ['Oradea', 'Arad', 'Bimnicu Vilcea', 'Fagaras'], + +'Timisoara': ['Arad', 'Lugoj'], + +'Mehadia': ['Lugoj', 'Dobreta'], + +'Bimnicu Vilcea': ['Sibiu', 'Pitesti', 'Craiova'], + +'Fagaras': ['Sibiu', 'Bucharest'], + +'Giurgiu': ['Bucharest'], + +'Vaslui': ['Urziceni','Iasai'], + +'Neaput': ['Tagai'] +} + +def IDDES(root, goal): + depth = 0 + while True: + print("Looping at depth %i"%(depth)) + result = DLS(root, goal, depth) + print ("Result: %s, Goal: %s" % (result, goal)) + if result == goal: + return result + depth = depth +1 + +def DLS(node, goal, depth): + print ("node: %s, goal %s, depth: %i" % (node, goal, depth)) + if depth == 0 and node == goal: + print("---Found goal, returning ---") + return node + elif depth > 0: + print("Looping through children %s" %(graph.get(node, []))) + for child in graph.get(node, []): + if goal == DLS(child, goal, depth-1): + return goal + +IDDES('Arad', 'Bucharest') \ No newline at end of file