0% found this document useful (0 votes)
16 views8 pages

AIMLL 1(a), (b)[1]

The document outlines an assignment requiring the implementation of Breadth First Search (BFS) and Depth First Search (DFS) for the Water Jug problem. It provides a detailed explanation of both algorithms, including their theoretical foundations, key features, and algorithm steps, along with code examples for each implementation. The assignment also includes acceptance criteria and a conclusion discussing the applications and suitability of BFS and DFS in solving graph and state-space problems.

Uploaded by

changuu6969
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views8 pages

AIMLL 1(a), (b)[1]

The document outlines an assignment requiring the implementation of Breadth First Search (BFS) and Depth First Search (DFS) for the Water Jug problem. It provides a detailed explanation of both algorithms, including their theoretical foundations, key features, and algorithm steps, along with code examples for each implementation. The assignment also includes acceptance criteria and a conclusion discussing the applications and suitability of BFS and DFS in solving graph and state-space problems.

Uploaded by

changuu6969
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Assignment No.

1 Assignment Date:

Title: A) Write a Program to Implement Breadth First Search. Submission Date: 07/02/2025
B) Implementation of Depth First Search for Water Jug problem
Problem Statement:
A) Write a Program to Implement Breadth First Search.
B) Implementation of Depth First Search for Water Jug problem
Theory:

A)What is Breadth-First Search?

The Breadth-First Search is a traversing algorithm used to satisfy a given property by searching the tree or
graph data structure. It belongs to uninformed or blind search AI algorithms as It operates solely based on the
connectivity of nodes and doesn't prioritize any particular path over another based on heuristic knowledge or
domain-specific information. it doesn't incorporate any additional information beyond the structure of the
search space. It is optimal for unweighted graphs and is particularly suitable when all actions have the same
cost. Due to its systematic search strategy, BFS can efficiently explore even infinite state spaces. The graph
structure of BFS allows to work as follows:

BFS for AI-


Originally it starts at the root node, then it expands all of its successors, it systematically explores all its
neighbouring nodes before moving to the next level of nodes. ( As shown in the above image, It starts from the
root node A then expands its successors B)
This process of extending the root node’s immediate neighbours, then to their neighbours, and so on, lasts until
all the nodes within the graph have been visited or until the specific condition is met. From the above image
we can observe that after visiting the node B it moves to node C. when the level 1 is completed, it further
moves to the next level i.e 2 and explore node D. it will move systematically to node E, node F and node G.
After visiting the node G it will terminate.

Key Features of BFS

Level-by-Level Exploration: BFS explores all nodes at the same depth before proceeding to deeper levels.

Optimality: BFS guarantees the shortest path in an unweighted graph when the solution lies in the shallowest
level.
Completeness: If a solution exists, BFS will find it.

Space Complexity: BFS uses a queue to store nodes, leading to potentially high space complexity, especially
in wide graphs.

Time Complexity: O(V+E),


where
V is the number of vertices and
E is the number of edges.

B)What is a Depth-First Search in AI?

Depth-first search is a traversing algorithm used in tree and graph-like data structures. It generally starts
by exploring the deepest node in the frontier. Starting at the root node, the algorithm proceeds to search to
the deepest level of the search tree until nodes with no successors are reached.Suppose the node with
unexpanded successors is encountered then the search backtracks to the next deepest node to explore
alternative paths.

Depth-first search (DFS) explores a graph by selecting a path and traversing it as deeply as possible before
backtracking.

Originally it starts at the root node, then it expands all of its one branch until it reaches a dead end, then
backtracks to the most recent unexplored node, repeating until all nodes are visited or a specific condition is
met. ( As shown in the above image, starting from node A, DFS explores its successor B, then proceeds to its
descendants until reaching a dead end at node D. It then backtracks to node B and explores its remaining
successors i.e E. )
This systematic exploration continues until all nodes are visited or the search terminates. (In our case after
exploring all the nodes of B. DFS explores the right side node i.e C then F and and then G. After exploring the
node G. All the nodes are visited. It will terminate.

In the water jug problem in Artificial Intelligence, we are provided with two jugs: one having the
capacity to hold 3 gallons of water and the other has the capacity to hold 4 gallons of water. There is
no other measuring equipment available and the jugs also do not have any kind of marking on them.
So, the agent’s task here is to fill the 4-gallon jug with 2 gallons of water by using only these two
jugs and no other material. Initially, both our jugs are empty.
So, to solve this problem, following set of rules were proposed:
Production rules for solving the water jug problem
Solution:
The state space for this problem can be described as the set of ordered pairs of integers (x,y)
Where,
X represents the quantity of water in the 4-gallon jug X= 0,1,2,3,4
Y represents the quantity of water in 3-gallon jug Y=0,1,2,3
Start State: (0,0)
Goal State: (2,0)
Generate production rules for the water jug problem

Initialization:
Start State: (0,0)
Apply Rule 2:
(X,Y | Y<3) -> (X,3)
{Fill 3-gallon jug} Now the state is (X,3) Iteration 1:
Current State: (X,3) Apply Rule 7:
(X,Y | X+Y<=4 ^Y>0) (X+Y,0)
{Pour all water from 3-gallon jug into 4-gallon jug} Now the state is (3,0)
Iteration 2: Current State : (3,0)
Apply Rule 2: (X,Y | Y<3) -> (3,3)
{Fill 3-gallon jug} Now the state is (3,3) Iteration 3:
Current State:(3,3)
Apply Rule 5:
(X,Y | X+Y>=4 ^ Y>0) (4,Y-(4-X))
{Pour water from 3-gallon jug into 4-gallon jug until 4-gallon jug is full} Now the state is (4,2)
Iteration 4:
Current State : (4,2) Apply Rule 3:
(X,Y | X>0)
(0,Y)
{Empty 4-gallon jug} Now state is (0,2) Iteration 5:
Current State : (0,2) Apply Rule 9:
(0,2)
(2,0)
{Pour 2 gallon water from 3 gallon jug into 4 gallon jug} Now the state is (2,0)

Acceptance Criteria:
(list of scenarios to be completed in solution for completing assignments)

Sr. No. Acceptance Criteria Remarks Instructor


(completed/ Not completed)
1
2

3
4
5
Algorithm with complexity analysis:
BFS:

Algorithm Steps

1. Initialize:
o
Start with the initial node (root node).
o
Use a queue to keep track of nodes to visit.
o
Mark the starting node as visited.
2. Expand Nodes:
o
Dequeue a node from the front of the queue.
o
Add all its unvisited neighbors to the queue and mark them as visited.
3. Repeat:
o
Continue the process until the queue is empty or the goal node is found.
4. Output:
o
If the goal node is found, output the path; otherwise, return failure.
DFS:

DFS Algorithm Steps:

1. Initialize:
o
Start with the initial node (root node).
o
Use a stack to keep track of nodes to visit.
o
Mark the starting node as visited.
2. Expand Nodes:
o
Pop a node from the top of the stack.
o
Add all its unvisited neighbors to the stack and mark them as visited.
o
Optionally, keep track of the path for backtracking or output purposes.

3. Repeat:
o
Continue the process until the stack is empty or the goal node is found.
4. Output:
o
If the goal node is found, output the path; otherwise, return failure.

Conclusion:

BFS and DFS are fundamental graph traversal techniques with distinct applications. BFS explores
nodes level by level using a queue, making it ideal for shortest-path problems. DFS, using a stack
(or recursion), explores as deep as possible before backtracking, useful in exhaustive searches like
the Water Jug problem. BFS is best for finding the shortest path, while DFS is effective in exploring
all possible states. The choice between them depends on the problem’s requirements. Both
algorithms play a crucial role in solving real-world graph and state-space problems.
Name of Student: Nikhil More
Roll No. 2223838
Class: TY Core- 5 Batch C
Enrolment no: MITU22BTCS0477
Subject: AIML Lab

Assignment no: 01 (A), (B)

Problem Statement-

A) Write a Program to Implement Breadth First Search.


B) Implementation of Depth First Search for Water Jug problem

Code-

A)
graph = {
'5': ['3', '7'],
'3': ['2', '4'],
'7': ['8'],
'2': [],
'4': ['8'],
'8': [],
}

visited = [] # List for visited nodes


queue = [] # Initialize a queue

def bfs(visited, graph, node): # Function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print(m, end=" ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search:")
bfs(visited, graph, '5') # Function calling

Output:

Following is the Breadth-First Search:


5 3 7 2 4 8
Code-

B)

# Water Jug Problem using Depth First Search (DFS)

def water_jug_dfs(x, y, target):


stack = [(0, 0)] # Initial state (0,0)
visited = set() # Keep track of visited states
path = [] # Store the sequence of steps

while stack:
current = stack.pop() # Get the last element (LIFO)

# If we already visited this state, skip


if current in visited:
continue

# Mark the state as visited


visited.add(current)
path.append(current)

# If we reach the target, return the path


if current[0] == target or current[1] == target:
return path

# Generate possible next states


a, b = current

next_states = [
(x, b), # Fill Jug 1
(a, y), # Fill Jug 2
(0, b), # Empty Jug 1
(a, 0), # Empty Jug 2
(a - min(a, y - b), b + min(a, y - b)), # Pour Jug 1 -> Jug 2
(a + min(b, x - a), b - min(b, x - a)) # Pour Jug 2 -> Jug 1
]

# Add new states to the stack if not visited


for state in next_states:
if state not in visited:
stack.append(state)

return None # No solution found

# Example usage
x = 4 # Capacity of Jug 1
y = 3 # Capacity of Jug 2
target = 2 #Desired amount of water

solution = water_jug_dfs(x, y, target)


if solution:
print("Solution path:", solution)
else:
print("No solution possible")

OUTPUT:
Solution path: [(0, 0), (0, 3), (3, 0), (3, 3), (4, 2)]

You might also like