Professional Documents
Culture Documents
Aim 3
Aim 3
Lab Session: 3
Experiment 3
Number
Experiment Title To implement Depth First Search algorithm using Python.
Concept Depth-First Search (DFS) is a graph traversal algorithm that explores as far
as possible along each branch before backtracking.
DFS explores deeply into the graph structure before backtracking, which
means it prioritizes going as deep as possible along each branch before
exploring other branches.
Program class Node: def __init__(self, state,
parent=None):
self.state = state
self.parent = parent
self.children = []
if current_node.state == goal_state:
return get_path(current_node)
visited.add(current_node.state)
return None
def get_children(state):
# Define the corrected branching logic based on the problem
description if state == 'A':
return ['B', 'C']
elif state == 'B':
return ['D', 'E']
elif state == 'C':
return ['F', 'G']
elif state == 'G':
return ['H', 'I']
else: return []
def get_path(node):
path = []
while node:
path.insert(0, node.state)
node = node.parent return
path
# Example usage
initial_state = 'A' goal_state
= 'H'
result = depth_first_search(initial_state, goal_state)
if result:
print(f"Path from {initial_state} to {goal_state}: {result}") else:
print(f"No path found from {initial_state} to {goal_state}")
Result
Conclusion
The “depth_first_search” function conducts the DFS traversal, maintaining
a stack to keep track of nodes to explore. It terminates when it finds the
goal state or exhausts all possible paths. The “get_children” function
defines the branching logic for generating child states based on the
current state.
The “get_path” function retrieves the path from the goal state to the
initial state by tracing back through the parent nodes.