def pour_water_dfs(jug1_capacity, jug2_capacity, target_amount, jug1=0, jug2=0, visited=set(),
path=[]):
if (jug1, jug2) in visited:
return False
visited.add((jug1, jug2))
if jug1 == target_amount or jug2 == target_amount:
print("Steps and States to achieve", target_amount, ":")
for step, state in path:
print(step, "\t\t\t", state)
return True
if jug1 < jug1_capacity:
if pour_water_dfs(jug1_capacity, jug2_capacity, target_amount, jug1_capacity, jug2, visited, path +
[("Fill jug 1", (jug1_capacity, jug2))]):
return True
if jug2 < jug2_capacity:
if pour_water_dfs(jug1_capacity, jug2_capacity, target_amount, jug1, jug2_capacity, visited, path +
[("Fill jug 2", (jug1, jug2_capacity))]):
return True
if jug1 > 0:
if pour_water_dfs(jug1_capacity, jug2_capacity, target_amount, 0, jug2, visited, path + [("Empty jug
1", (0, jug2))]):
return True
if jug2 > 0:
if pour_water_dfs(jug1_capacity, jug2_capacity, target_amount, jug1, 0, visited, path + [("Empty jug
2", (jug1, 0))]):
return True
if jug1 > 0 and jug2 < jug2_capacity:
pour_amount = min(jug1, jug2_capacity - jug2)
if pour_water_dfs(jug1_capacity, jug2_capacity, target_amount, jug1 - pour_amount, jug2 +
pour_amount, visited, path + [("Pour from jug 1 to jug 2", (jug1 - pour_amount, jug2 + pour_amount))]):
return True
if jug2 > 0 and jug1 < jug1_capacity:
pour_amount = min(jug2, jug1_capacity - jug1)
if pour_water_dfs(jug1_capacity, jug2_capacity, target_amount, jug1 + pour_amount, jug2 -
pour_amount, visited, path + [("Pour from jug 2 to jug 1", (jug1 + pour_amount, jug2 - pour_amount))]):
return True
return False
# Example usage:
jug1_capacity = 4
jug2_capacity = 3
target_amount = 2
pour_water_dfs(jug1_capacity, jug2_capacity, target_amount)