Practical 1 BFS
Practical 1 BFS
BFS
CODE :
class Graph:
def __init__(self, graph_dict=None, directed=True):
self.graph_dict = graph_dict or {}
self.directed = directed
def nodes(self):
return list(self.graph_dict.keys())
def get(self, a, b=None):
links = self.graph_dict.get(a)
if b is None:
return links
else:
cost = links.get(b)
return cost
class Problem:
def __init__(self, initial, goal=None):
self.initial = initial
self.goal = goal
class Node:
def __init__(self, state, parent=None, action=None, path_cost=0):
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
self.depth = 0
if parent:
self.depth = parent.depth + 1
def __repr__(self):
return "<Node "+ self.state + ">"
def expand(self, problem):
children = []
for action in problem.actions(self.state):
x=self.child_node(problem,action)
children.append(x)
return children
def child_node(self, problem, action):
next_state = problem.result(self.state, action)
new_cost = problem.path_cost(self.path_cost, self.state,action,next_state)
next_node = Node(next_state, self, action,new_cost )
return next_node
def path(self):
node, path_back = self, []
while node:
path_back.append(node)
node = node.parent
return list(reversed(path_back))
def solution(self):
return [node.state for node in self.path()]
mumbaigraph= Graph({'mumbai':{'pune':119,'thane':29},
'pune':{'mumbai':119,'solapur':230, ' Osmanabad ':233},
'thane':{'mumbai':29,'pune':120},
'solapur':{'pune':230,'Osmanabad':68},
'Osmanabad':{'solapur':68} }, False)
print("---BFS----")
finalnode = breadth_first_search(mumbaigraph_problem)
if (finalnode is not None ) :
print("solution of ", mumbaigraph_problem.initial, " to ",
mumbaigraph_problem.goal, finalnode.solution())
print("path cost of final node =", finalnode.path_cost)
else:
print("path does not exists")
OUTPUT :