You are on page 1of 2

12/17/22, 3:52 AM WaterAndJug_Problem.

py
1 from collections import deque
2 def BFS(a, b, target):
3
4 # Map is used to store the states, every
5 # state is hashed to binary value to
6 # indicate either that state is visited
7 # before or not
8 m = {}
9 isSolvable = False
10 path = []
11
12 # Queue to maintain states
13 q = deque()
14
15 # Initialing with initial state
16 q.append((0, 0))
17
18 while (len(q) > 0):
19
20 # Current state
21 u = q.popleft()
22
23 # q.pop() #pop off used state
24
25 # If this state is already visited
26 if ((u[0], u[1]) in m):
27 continue
28
29 # Doesn't met jug constraints
30 if ((u[0] > a or u[1] > b or
31 u[0] < 0 or u[1] < 0)):
32 continue
33
34 # Filling the vector for constructing
35 # the solution path
36 path.append([u[0], u[1]])
37
38 # Marking current state as visited
39 m[(u[0], u[1])] = 1
40
41 # If we reach solution state, put ans=1
42 if (u[0] == target or u[1] == target):
43 isSolvable = True
44
45 if (u[0] == target):
46 if (u[1] != 0):
47
48 # Fill final state
49 path.append([u[0], 0])
50 else:
51 if (u[0] != 0):
52
53 # Fill final state
54 path.append([0, u[1]])
55
56 # Print the solution path
57 sz = len(path)
58 for i in range(sz):
59 print("(", path[i][0], ",",
60 path[i][1], ")")
61 break
62
63 # If we have not reached final state
64 # then, start developing intermediate
65 # states to reach solution state
66 q.append([u[0], b]) # Fill Jug2
67 q.append([a, u[1]]) # Fill Jug1
68
69 for ap in range(max(a, b) + 1):
70
71 # Pour amount ap from Jug2 to Jug1
72 c = u[0] + ap
73 d = u[1] - ap
74
75 # Check if this state is possible or not
76 if (c == a or (d == 0 and d >= 0)):
77 q.append([c, d])
78

localhost:4649/?mode=python 1/2
12/17/22, 3:52 AM WaterAndJug_Problem.py
79 # Pour amount ap from Jug 1 to Jug2
80 c = u[0] - ap
81 d = u[1] + ap
82
83 # Check if this state is possible or not
84 if ((c == 0 and c >= 0) or d == b):
85 q.append([c, d])
86
87 # Empty Jug2
88 q.append([a, 0])
89
90 # Empty Jug1
91 q.append([0, b])
92
93 # No, solution exists if ans=0
94 if (not isSolvable):
95 print("No solution")
96 if __name__ == '__main__':
97
98 Jug1, Jug2, target = 4, 3, 2
99 print("Path from initial state "
100 "to solution state ::")
101
102 BFS(Jug1, Jug2, target)
103
104

localhost:4649/?mode=python 2/2

You might also like