最近在王晓华老师算法课程中学习到用穷举法解决三个水桶等分8升水。
还是用python来实现一下加深了解
其中用到递归思想,每次向函数中传入当前各桶中水量,以及从第几个倒水状态开始遍历
import pandas as pd
fixed=[[0,1],[0,2],[1,0],[1,2],[2,0],[2,1]] # 固定6种倒水方式
state=pd.DataFrame(columns=["buc0","buc1","buc2"]) # 8 3 5
state = state.append({'buc0': 8,'buc1':0,'buc2':0}, ignore_index=True)
volumn=[8,3,5] # 桶的容量
state_col=state.columns
num=0
def take_action(state,num):
current=state.loc[len(state)-1][state_col]
if current[state_col[0]]==4 and current[state_col[2]]==4:
return state
else:
for id in range(num,6):
if current[state_col[fixed[id][0]]]>0 and current[state_col[fixed[id][1]]]<volumn[fixed[id][1]]:
if (volumn[fixed[id][1]]-current[state_col[fixed[id][1]]])>current[state_col[fixed[id][0]]]:
current[state_col[fixed[id][1]]]=current[state_col[fixed[id][1]]]+current[state_col[fixed[id][0]]]
current[state_col[fixed[id][0]]]=0
state=state.append(current,ignore_index=True)
else:
current[state_col[fixed[id][0]]]=current[state_col[fixed[id][0]]]-(volumn[fixed[id][1]]-current[state_col[fixed[id][1]]])
current[state_col[fixed[id][1]]]=volumn[fixed[id][1]]
state=state.append(current,ignore_index=True)
if len(state)==len(state.drop_duplicates()):
state=take_action(state,0)
return state
else:
state=take_action(state.drop_duplicates(),id+1) # 当前得到的状态废除 原状态从子状态0开始遍历
return state
output=take_action(state,0)
输出结果为: