function waterJugProblem(A, B, C):
# A, B: capacities of the two jugs
# C: the target amount of water to be measured
# Initialize visited states to avoid cycles
visited = set()
# Queue to store states; each state is a tuple (amount in jug A, amount in jug B)
queue = [(0, 0)] # Start with both jugs empty
# BFS Loop
while queue is not empty:
currentA, currentB = [Link]() # Dequeue a state
# If we reached the goal, return True
if currentA == C or currentB == C:
return True
# Generate possible next states and enqueue them if not visited
nextStates = [
(A, currentB), # Fill jug A
(currentA, B), # Fill jug B
(0, currentB), # Empty jug A
(currentA, 0), # Empty jug B
(max(0, currentA - (B - currentB)), min(B, currentA + currentB)), # Pour from A to B
(min(A, currentA + currentB), max(0, currentB - (A - currentA))) # Pour from B to A
for state in nextStates:
if state not in visited:
[Link](state) # Mark this state as visited
[Link](state) # Enqueue the state
# If no solution was found
return False