我是靠谱客的博主 奋斗大船,这篇文章主要介绍程序解:现有3L容器和5L容器各一个,问如何量出4L水(水无限),现在分享给大家,希望可以做个参考。

穷举所有的可能性,从杯子里面水变化角度来讲,每个状态到下一个状态只有6种行为:3L杯子装满,5L杯子装满,3L倒空,5L倒空,3L倒到5L,5L倒到3L。最终结果如果5L的里面有4L水则得到一个解。如果当前状态和前面一个状态重复,则取消继续往后的探索。


复制代码
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
public class test{ private static Status[] steps = new Status[100]; public static void main(String[] args){ steps[0] = new Status(); solve(1); } private static void solve(final int depth){ //paint(depth-1); if(duplicate(depth - 1)){ return; } if(steps[depth - 1].cup5 == 4){ paint(depth - 1); return; } Status preStatus = steps[depth - 1]; steps[depth] = preStatus.full3(); solve(depth + 1); steps[depth] = preStatus.full5(); solve(depth + 1); steps[depth] = preStatus.trans3to5(); solve(depth + 1); steps[depth] = preStatus.trans5to3(); solve(depth + 1); steps[depth] = preStatus.empty3(); solve(depth + 1); steps[depth] = preStatus.empty5(); solve(depth + 1); } private static boolean duplicate(int depth){ for(int i=0 ; i < depth ; i++){ if( steps[i].equals(steps[depth])){ return true; } } return false; } private static void paint(int depth){ for(int i = 0; i <= depth; i++){ System.out.print(steps[i]+" "); } System.out.println(); } } class Status{ int cup3; int cup5; public Status(){ } public Status(Status s){ this.cup3 = s.cup3; this.cup5 = s.cup5; } public Status full3(){ Status newStatus = new Status(this); newStatus.cup3 = 3; return newStatus; } public Status full5(){ Status newStatus = new Status(this); newStatus.cup5 = 5; return newStatus; } public Status trans3to5(){ Status newStatus = new Status(this); if(5 - newStatus.cup5 >= newStatus.cup3){ newStatus.cup5 += newStatus.cup3; newStatus.cup3 = 0; }else{ newStatus.cup3 -= (5 - newStatus.cup5); newStatus.cup5 = 5; } return newStatus; } public Status trans5to3(){ Status newStatus = new Status(this); if(newStatus.cup5 <= 3 - newStatus.cup3){ newStatus.cup3 += newStatus.cup5; newStatus.cup5 = 0; }else{ newStatus.cup5 -= (3 - newStatus.cup3); newStatus.cup3 = 3; } return newStatus; } public Status empty3(){ Status newStatus = new Status(this); newStatus.cup3 = 0; return newStatus; } public Status empty5(){ Status newStatus = new Status(this); newStatus.cup5 = 0; return newStatus; } public String toString(){ return "["+this.cup3+"#"+this.cup5+"]"; } public boolean equals(Object o){ if(o == null){ return false; } if(o == this){ return true; } if(o instanceof Status){ Status s = (Status)o; return s.cup3 == this.cup3 && s.cup5 == this.cup5; } return false; } }


最后

以上就是奋斗大船最近收集整理的关于程序解:现有3L容器和5L容器各一个,问如何量出4L水(水无限)的全部内容,更多相关程序解:现有3L容器和5L容器各一个内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部