water jug
from collections import deque
def water_jug_bfs(capacity_a, capacity_b, target):
visited = set()
queue = deque([(0, 0)])
while queue:
current_state = queue.popleft()
a, b = current_state
if current_state in visited:
continue
visited.add(current_state)
if a == target or b == target:
print("Target amount reached:", current_state)
return
queue.append((0, b))
queue.append((a, 0))
queue.append((capacity_a, b))
queue.append((a, capacity_b))
queue.append((a - min(a, capacity_b - b), b + min(a, capacity_b - b)))
queue.append((a + min(b, capacity_a - a), b - min(b, capacity_a - a)))
print("Target amount not reachable with the given jug capacities.")
# Example usage:
jug_capacity_a = 4
jug_capacity_b = 3
target_amount = 2
print(f"Solving Water Jug problem for capacities ({jug_capacity_a}, {jug_capacity_b}) to measure {target_amount} units of water.")
water_jug_bfs(jug_capacity_a, jug_capacity_b, target_amount)
Comments
Post a Comment