Aiml 2
Aiml 2
Experiment No. 2
DFS
class Map:
def init (self, nodes):
self.nodes_count = nodes
self.edges = defaultdict(list)
explored = set()
node_stack = [(start_point, 0)]
route_parent = {start_point: None}
total_cost = {start_point: 0}
while node_stack:
current_node, cumulative_cost = node_stack.pop()
if current_node in explored:
continue
explored.add(current_node)
print(f"Visited: {current_node}, Cost from start: {cumulative_cost}")
if current_node == destination:
break
for neighbor, path_cost in reversed(self.edges[current_node]):
if neighbor not in explored:
node_stack.append((neighbor, cumulative_cost + path_cost))
route_parent[neighbor] = current_node
total_cost[neighbor] = cumulative_cost + path_cost
route = []
if destination in route_parent:
step = destination
while step is not None:
route.append(step)
step = route_parent[step]
route.reverse()
if route:
total_path_cost = total_cost[destination]
print("Path from", start_point, "to", destination, ":", " ->
".join(route))
print("Total cost from start to end:", total_path_cost)
else:
print("No path found from", start_point, "to", destination)
# Example usage
m = Map(20)
m.depth_first_search('Oradea', 'Bucharest')
RESULT:
BFS
PROGRAM:
class MapTraversal:
def init (self, nodes):
self.node_count = nodes
self.connections = defaultdict(list)
while loc_queue:
current_location, cumulative_cost = loc_queue.popleft()
if current_location == destination:
break
route = []
if destination in route_parent:
step = destination
while step is not None:
route.append(step)
step = route_parent[step]
route.reverse()
if route:
total_path_cost = total_cost[destination]
print("Path from", start_point, "to", destination, ":", " ->
".join(route))
print("Total cost from start to end:", total_path_cost)
else:
print("No path found from", start_point, "to", destination)
# Example usage
m = MapTraversal(20)
m.breadth_first_search('Oradea', 'Bucharest')
w
RESULT: