Lab Program 1
Lab Program 1
Algorithm
The algorithm for solving the Water Jug Problem using DFS involves
exploring all possible states and transitions between them until the
desired quantity of water is achieved. Here are the high-level steps of the
algorithm:
1.Create a stack to store the states of the jugs.
2.Initialize the stack with the initial state (both jugs empty).
3.While the stack is not empty, do the following:
1. Pop a state from the stack.
2. If the state represents the desired quantity, stop and return the
solution.
3. Generate all possible next states from the current state.
4. Push the next states onto the stack.
4.If the stack becomes empty and no solution is found, the problem is
unsolvable.
Pseudocode
function solveWaterJugProblem(capacity_jug1, capacity_jug2,
desired_quantity):
stack = empty stack
push initial state (0, 0) onto stack
The Python implementation of the Water Jug Problem using the DFS
algorithm:
def solveWaterJugProblem(capacity_jug1, capacity_jug2, desired_quantity):
stack = []
stack.append((0, 0)) # Initial state: both jugs empty
while stack:
current_state = stack.pop()
The Python implementation of the Water Jug Problem using the DFS
algorithm:
def generateNextStates(state, capacity_jug1, capacity_jug2):
next_states = []
# Fill Jug 1
next_states.append((capacity_jug1, state[1]))
# Fill Jug 2
next_states.append((state[0], capacity_jug2))
# Empty Jug 1
next_states.append((0, state[1]))
# Empty Jug 2
next_states.append((state[0], 0))
The Python implementation of the Water Jug Problem using the DFS
algorithm:
# Pour water from Jug 1 to Jug 2
pour_amount = min(state[0], capacity_jug2 - state[1])
next_states.append((state[0] - pour_amount, state[1] + pour_amount))
return next_states
solution = solveWaterJugProblem(4, 3, 2)
print("Solution:", solution)
Solution: (4, 2)
Explanation
• The algorithm starts with an empty stack and pushes the initial state (both
jugs empty) onto the stack.
• While the stack is not empty, it pops a state from the stack, checks if the state
represents the desired quantity, generates all possible next states from the
current state, and pushes them onto the stack.
• This process continues until the stack becomes empty or the desired quantity
is found.
• The solveWaterJugProblem function takes the capacities of the two jugs and the
desired quantity as input.
• It initializes an empty stack and pushes the initial state onto the stack.
• In each iteration, it checks if the current state satisfies the desired quantity.
• If not, it generates the next states based on the available operations (filling,
emptying, and pouring) and pushes them onto the stack.
• Once the desired quantity is found, the function returns the current state.
• If the stack becomes empty without finding a solution, it returns a message
indicating that no solution was found.
• The generateNextStates function generates all possible next states from a given
state by considering the available operations for each jug.
Conclusion