-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5_WaterJug.py
66 lines (56 loc) · 2.33 KB
/
5_WaterJug.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def water_jug_dfs(jug1_capacity, jug2_capacity, target_capacity):
def dfs(jug1, jug2, path):
if jug1 == target_capacity or jug2 == target_capacity:
print("Solution Found : ", path)
return
# Fill jug1
if jug1 < jug1_capacity:
new_jug1 = jug1_capacity
new_jug2 = jug2
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path+f"Fill Jug1\n")
# Fill jug2
if jug2 < jug2_capacity:
new_jug1 = jug1
new_jug2 = jug2_capacity
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path+f"Fill Jug2\n")
# Pour water from jug1 to jug2
if jug1 > 0 and jug2 < jug2_capacity:
pour_amount = min(jug1, jug2_capacity-jug2)
new_jug1 = jug1 - pour_amount
new_jug2 = jug2+pour_amount
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path+f"Pour Jug1 into Jug2\n")
# Pour water from jug2 to jug1
if jug2 > 0 and jug1 < jug1_capacity:
pour_amount = min(jug2, jug1_capacity-jug1)
new_jug1 = jug1 + pour_amount
new_jug2 = jug2 - pour_amount
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path+f"Pour Jug2 into Jug1\n")
# Empty jug1
if jug1 > 0:
new_jug1 = 0
new_jug2 = jug2
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path+f"Empty jug1\n")
# Empty jug2
if jug2 > 0:
new_jug1 = jug1
new_jug2 = 0
if (new_jug1, new_jug2) not in visited:
visited.add((new_jug1, new_jug2))
dfs(new_jug1, new_jug2, path+f"Empty jug2\n")
visited = set()
dfs(0, 0, "")
if __name__ == '__main__':
jug1_capacity = 4
jug2_capacity = 3
target_capacity = 2
water_jug_dfs(jug1_capacity, jug2_capacity, target_capacity)