Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions bfs.py
Original file line number Diff line number Diff line change
@@ -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())

61 changes: 61 additions & 0 deletions dfs.py
Original file line number Diff line number Diff line change
@@ -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')