Q: Implement & Demonstrate Depth First Search Algorithm on Water Jug Problem.
Algorithm:
1. Input Initialization:
• Read integers a, b, and c from the user, representing the capacities of jug1,
jug2, and the target amount of water (aim), respectively.
• Initialize jug1 with a, jug2 with b, and aim with c.
2. Visited States Initialization:
• Create a defaultdict named visited with a default value of False to keep
track of visited states.
3. Define Recursive Function waterSolver(amt1, amt2):
• Goal Test:
• If (amt1 == aim and amt2 == 0) or (amt1 == 0 and amt2 ==
aim), print (amt1, amt2) and return True.
• If State Not Visited:
• Print (amt1, amt2).
• Mark the state (amt1, amt2) as visited.
• Recursively call waterSolver for the following states:
1. Empty the first jug: waterSolver(0, amt2).
2. Empty the second jug: waterSolver(amt1, 0).
3. Fill the first jug: waterSolver(jug1, amt2).
4. Fill the second jug: waterSolver(amt1, jug2).
5. Pour water from the second jug to the first jug:
• Calculate the new state: (amt1 + min(amt2, jug1 -
amt1), amt2 - min(amt2, jug1 - amt1)).
• Call waterSolver with the new state.
6. Pour water from the first jug to the second jug:
• Calculate the new state: (amt1 - min(amt1, jug2 -
amt2), amt2 + min(amt1, jug2 - amt2)).
• Call waterSolver with the new state.
• Return True if any of the recursive calls return True, otherwise return
False.
• If State Already Visited:
• Return False.
4. Final Execution:
• Print "steps".
• Call waterSolver(0, 0) to start the process with both jugs initially empty.
Pseudocode:
Input a, b, c
jug1 = a
jug2 = b
aim = c
visited = defaultdict(False)
Function waterSolver(amt1, amt2):
If (amt1 == aim and amt2 == 0) or (amt1 == 0 and amt2 == aim):
Print amt1, amt2
Return True
If visited[(amt1, amt2)] == False:
Print amt1, amt2
visited[(amt1, amt2)] = True
Return waterSolver(0, amt2) OR
waterSolver(amt1, 0) OR
waterSolver(jug1, amt2) OR
waterSolver(amt1, jug2) OR
waterSolver(amt1 + min(amt2, jug1 - amt1), amt2 -
min(amt2,jug1 - amt1)) OR
waterSolver(amt1 - min(amt1, jug2 - amt2), amt2 +
min(amt1, jug2 - amt2))
Else:
Return False
Print "steps"
Call waterSolver(0, 0)