1
+ from collections import deque
2
+
3
+ def BFS (b1 , b2 , initial_state , goal_state ):
4
+ # Map is used to store the states
5
+ map = {}
6
+ isSolvable = False
7
+ path = []
8
+
9
+ queue = deque () # Queue to maintain states
10
+
11
+ queue .append (initial_state ) # Initialing with initial state
12
+
13
+ while (len (queue ) > 0 ):
14
+ # Current state
15
+ current_state = queue .popleft ()
16
+
17
+ # If this state is already visited
18
+ if ((current_state [0 ], current_state [1 ]) in map ):
19
+ continue
20
+
21
+ # Doesn't met bottle constraints
22
+ if ((current_state [0 ] > b1 or current_state [1 ] > b2 or current_state [0 ] < 0 or current_state [1 ] < 0 )):
23
+ continue
24
+
25
+ # Filling the vector for constructing the solution path
26
+ path .append ([current_state [0 ], current_state [1 ]])
27
+
28
+ # Marking current state as visited
29
+ map [(current_state [0 ], current_state [1 ])] = 1
30
+
31
+ # Check Goal State
32
+ if (current_state [0 ] == goal_state [0 ] and current_state [1 ] == goal_state [1 ]):
33
+ isSolvable = True
34
+
35
+ # Print the solution path
36
+ solution_path = len (path )
37
+ for i in range (solution_path ):
38
+ print ("(" , path [i ][0 ], "," , path [i ][1 ], ")" )
39
+ break
40
+
41
+ # If we have not reached final state start developing intermediate states to reach solution state
42
+ queue .append ([current_state [0 ], b2 ]) # Fill Bottle 2
43
+ queue .append ([b1 , current_state [1 ]]) # Fill Bottle 1
44
+
45
+ for ap in range (max (b1 , b2 ) + 1 ):
46
+
47
+ # Pour amount ap from Bottle 2 to Bottle 1
48
+ c = current_state [0 ] + ap
49
+ d = current_state [1 ] - ap
50
+
51
+ # Check if this state is possible or not
52
+ if (c == b1 or (d == 0 and d >= 0 )):
53
+ queue .append ([c , d ])
54
+
55
+ # Pour amount ap from Bottle 1 to Bottle 2
56
+ c = current_state [0 ] - ap
57
+ d = current_state [1 ] + ap
58
+
59
+ # Check if this state is possible or not
60
+ if ((c == 0 and c >= 0 ) or d == b2 ):
61
+ queue .append ([c , d ])
62
+
63
+ # Empty Bottle 2
64
+ queue .append ([b1 , 0 ])
65
+
66
+ # Empty Bottle 1
67
+ queue .append ([0 , b2 ])
68
+
69
+ # No, solution exists if ans=0
70
+ if (not isSolvable ):
71
+ print (map )
72
+ print ("No solution" )
73
+
74
+
75
+ # Bottle Puzzle solve using BFS
76
+ if __name__ == '__main__' :
77
+
78
+ Bottle1 , Bottle2 = 10 , 8
79
+ initial_state = (0 ,0 )
80
+ goal_state = (2 ,8 )
81
+
82
+ print ("Path from initial state " "to solution state ::" )
83
+
84
+ BFS (Bottle1 , Bottle2 , initial_state , goal_state )
85
+
0 commit comments