22011A0554
CODE :
from collections import deque
import heapq
def get_next_states(state, capacities):
jug1, jug2 = state
max1, max2 = capacities
possible_states = []
possible_states.append(((max1, jug2), f"Fill Jug A ({max1}, {jug2})"))
possible_states.append(((jug1, max2), f"Fill Jug B ({jug1}, {max2})"))
possible_states.append(((0, jug2), f"Empty Jug A (0, {jug2})"))
possible_states.append(((jug1, 0), f"Empty Jug B ({jug1}, 0)"))
pourAtoB = min(jug1, max2 - jug2)
possible_states.append(((jug1 - pourAtoB, jug2 + pourAtoB), f"Pour A → B ({jug1 -
pourAtoB}, {jug2 + pourAtoB})"))
pourBtoA = min(jug2, max1 - jug1)
possible_states.append(((jug1 + pourBtoA, jug2 - pourBtoA), f"Pour B → A ({jug1 +
pourBtoA}, {jug2 - pourBtoA})"))
return possible_states
22011A0554
def solve_water_jug(search_type, capacities, target):
initial_state = (0, 0)
visited = set()
if search_type == "BFS":
queue = deque([(initial_state, [])])
elif search_type == "DFS":
queue = [(initial_state, [])]
elif search_type == "UCS":
queue = [(0, initial_state, [])]
heapq.heapify(queue)
while queue:
if search_type == "BFS":
state, path = queue.popleft()
elif search_type == "DFS":
state, path = queue.pop()
elif search_type == "UCS":
cost, state, path = heapq.heappop(queue)
if state in visited:
continue
22011A0554
visited.add(state)
if target in state:
return path + [f"Goal reached: {state}"]
for next_state, action in get_next_states(state, capacities):
if next_state not in visited:
if search_type in ["BFS", "DFS"]:
queue.append((next_state, path + [action]))
elif search_type == "UCS":
heapq.heappush(queue, (cost + 1, next_state, path + [action]))
return ["No solution found"]
def main():
jug1_capacity = int(input("Enter the capacity of Jug 1: "))
jug2_capacity = int(input("Enter the capacity of Jug 2: "))
target_amount = int(input("Enter the target amount of water: "))
print("\nChoose search method (BFS, DFS, UCS):")
search_type = input().strip().upper()
if search_type not in ["BFS", "DFS", "UCS"]:
22011A0554
print("Invalid search type. Please choose 'BFS', 'DFS', or 'UCS'.")
return
print(f"\n{search_type} Solution:")
solution = solve_water_jug(search_type, (jug1_capacity, jug2_capacity),
target_amount)
print("\n".join(solution))
if __name__ == "__main__":
main()
OUTPUT :
Enter the capacity of Jug 1: 4
Enter the capacity of Jug 2: 3
Enter the target amount of water: 2
Choose search method (BFS, DFS, UCS):
BFS
BFS Solution:
Fill Jug B (0, 3)
22011A0554
Pour B → A (3, 0)
Fill Jug B (3, 3)
Pour B → A (4, 2)
Goal reached: (4, 2)
Choose search method (BFS, DFS, UCS):
DFS
DFS Solution:
Fill Jug B (0, 3)
Pour B → A (3, 0)
Fill Jug B (3, 3)
Pour B → A (4, 2)
Goal reached: (4, 2)
Choose search method (BFS, DFS, UCS):
UCS
22011A0554
UCS Solution:
Fill Jug B (0, 3)
Pour B → A (3, 0)
Fill Jug B (3, 3)
Pour B → A (4, 2)
Goal reached: (4, 2)