You are on page 1of 6

DEPARTMENT OF BIOMEDICAL ENGINEERING

Academic Year: 2023-24

Lab Session: 3

Semester B.E. Semester VIII – Biomedical Engineering


Subject Artificial Intelligence
Subject Professor Prof. Priyanka Shrivastava
In-charge

Student Name Abhijit Gawai


Roll Number 20105A0021
Grade and Subject
Teacher’s Signature

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 works by:


Starting at a chosen node (usually the initial state).
Visiting an adjacent unvisited node.
Repeating step 2 until no adjacent unvisited nodes remain.
Backtracking to the previous node and repeating steps 2-3 until all nodes
have been visited.

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 = []

def depth_first_search(initial_state, goal_state):


initial_node = Node(initial_state) stack =
[initial_node] visited = set()
while stack:
current_node = stack.pop()

if current_node.state == goal_state:
return get_path(current_node)

visited.add(current_node.state)

# Add children to the stack in reverse order for depth-first search


for child_state in get_children(current_node.state): if
child_state not in visited:
child_node = Node(child_state, parent=current_node)
current_node.children.append(child_node)
stack.append(child_node)

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.

Overall, the code efficiently performs depth-first search to find a path


between two states in a graph.

You might also like