MOHAMMED SUHANA TARANNUM 23015A0518
WATER JUG PROBLEM:
from collections import deque
import heapq
def is_valid_state(x, y, a, b, visited):
return (x, y) not in visited and 0 <= x <= a and 0 <= y <= b
def get_neighbors(x, y, a, b):
return [
(a, y, "Fill Jug A"),
(x, b, "Fill Jug B"),
(0, y, "Empty Jug A"),
(x, 0, "Empty Jug B"),
(x - min(x, b - y), y + min(x, b - y), "Pour A -> B"),
(x + min(y, a - x), y - min(y, a - x), "Pour B -> A"),
]
def bfs(a, b, d):
queue = deque([(0, 0, [])])
visited = set()
while queue:
x, y, path = queue.popleft()
if x == d or y == d:
return path + [(x, y)]
visited.add((x, y))
for nx, ny, action in get_neighbors(x, y, a, b):
if is_valid_state(nx, ny, a, b, visited):
queue.append((nx, ny, path + [(x, y, action)]))
return None
MOHAMMED SUHANA TARANNUM 23015A0518
def dfs(a, b, d):
stack = [(0, 0, [])]
visited = set()
while stack:
x, y, path = stack.pop()
if x == d or y == d:
return path + [(x, y)]
visited.add((x, y))
for nx, ny, action in reversed(get_neighbors(x, y, a, b)):
if is_valid_state(nx, ny, a, b, visited):
stack.append((nx, ny, path + [(x, y, action)]))
return None
def ucs(a, b, d):
pq = [(0, 0, 0, [])] # (cost, x, y, path)
visited = set()
while pq:
cost, x, y, path = heapq.heappop(pq)
if x == d or y == d:
return path + [(x, y)]
visited.add((x, y))
for nx, ny, action in get_neighbors(x, y, a, b):
if is_valid_state(nx, ny, a, b, visited):
heapq.heappush(pq, (cost + 1, nx, ny, path + [(x, y, action)]))
return None
if __name__ == "__main__":
a = int(input("Enter capacity of Jug A: "))
b = int(input("Enter capacity of Jug B: "))
MOHAMMED SUHANA TARANNUM 23015A0518
d = int(input("Enter amount to measure: "))
print("BFS:", bfs(a, b, d))
print("DFS:", dfs(a, b, d))
print("UCS:", ucs(a, b, d))
OUTPUT: