最近面微信让做这道题
-
题目:
给一个装满水的 8 升满壶和两个分别是 5 升、3 升的空壶,想个办法,使得其中一个水壶恰好装 4 升水,每一步的操作只能是倒空或倒满 -
思路:
遍历+状态记忆
最终结果不是最优的。。问题应该是返回条件不太对,但是没想到怎么改,先放出来吧
class State:
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c
s1 = State(8,0,0)
A,B,C = 8,5,3
memo = [ ]
action = {
0:'将杯子A的水倒完给B',
1:'将杯子A的水倒满给B',
2:'将杯子A的水倒完给C',
3:'将杯子A的水倒满给C',
4:'将杯子B的水倒完给A',
5:'将杯子B的水倒满给A',
6:'将杯子B的水倒完给C',
7:'将杯子B的水倒满给C',
8:'将杯子C的水倒完给A',
9:'将杯子C的水倒满给A',
10:'将杯子C的水倒完给B',
11:'将杯子C的水倒满给B'
}
def bfs(state,line):
if state.a == target or state.b == target or state.c == target:
print(line)
return
for i in range(len(action)):
if (state.a,state.b,state.c,i) in memo:
continue
memo.append((state.a,state.b,state.c,i))
if i == 0:
if state.a == 0:
continue
if state.a + state.b < B:
line.append(action[i])
state_next = State(0,state.b+state.a,state.c)
bfs(state_next,line)
line.pop(-1)
if i == 1:
if state.a == 0:
continue
if state.a + state.b >= B and state.b != B:
line.append(action[i])
state_next = State(state.a - (B-state.b),B,state.c)
bfs(state_next,line)
line.pop(-1)
if i == 2:
if state.a == 0:
continue
if state.a + state.c < C:
line.append(action[i])
state_next = State(0,state.b,state.c+state.a)
bfs(state_next,line)
line.pop(-1)
if i == 3:
if state.a == 0:
continue
if state.a + state.c >= C and state.c != C:
line.append(action[i])
state_next = State(state.a - (C-state.c),state.b,C)
bfs(state_next,line)
line.pop(-1)
if i == 4:
if state.b == 0:
continue
if state.b + state.a < A:
line.append(action[i])
state_next = State(state.a+state.b,0,state.c)
bfs(state_next,line)
line.pop(-1)
if i == 5:
if state.b == 0:
continue
if state.a + state.b >= A and state.a != A:
line.append(action[i])
state_next = State(A,state.b - (A-state.a),state.c)
bfs(state_next,line)
line.pop(-1)
if i == 6:
if state.b == 0:
continue
if state.b + state.c < C:
line.append(action[i])
state_next = State(state.a,0,state.c+state.b)
bfs(state_next,line)
line.pop(-1)
if i == 7:
if state.b == 0:
continue
if state.b + state.c >= C and state.c != C:
line.append(action[i])
state_next = State(state.a,state.b - (C-state.c),C)
bfs(state_next,line)
line.pop(-1)
if i == 8:
if state.c == 0:
continue
if state.a + state.c < A:
line.append(action[i])
state_next = State(state.a+state.c,state.b,0)
bfs(state_next,line)
line.pop(-1)
if i == 9:
if state.c == 0:
continue
if state.a + state.c >= A and state.a != A:
line.append(action[i])
state_next = State(A,state.b,state.c - (A-state.a))
bfs(state_next,line)
line.pop(-1)
if i == 10:
if state.c == 0:
continue
if state.b + state.c < B:
line.append(action[i])
state_next = State(state.a,state.b+state.c,0)
bfs(state_next,line)
line.pop(-1)
if i == 11:
if state.c == 0:
continue
if state.b + state.c >= B and state.b != B:
line.append(action[i])
state_next = State(state.a,B,state.c - (B-state.b))
bfs(state_next,line)
line.pop(-1)
target = 4
bfs(s1,[ ])