from collections import defaultdict
def dfs():
capacities = (10, 7, 3)
initial = (10, 0, 0)
visited = set([initial])
parent = {initial: None}
move_taken = {initial: None}
def dfs_helper(state):
if state[0] == 5:
return state
for i in range(3):
for j in range(3):
if i == j:
continue
if state[i] == 0 or state[j] == capacities[j]:
continue
amount = min(state[i], capacities[j] - state[j])
new_state = list(state)
new_state[i] -= amount
new_state[j] += amount
new_state = tuple(new_state)
if new_state not in visited:
visited.add(new_state)
parent[new_state] = state
move_taken[new_state] = (i, j, amount)
result = dfs_helper(new_state)
if result:
return result
return None
final_state = dfs_helper(initial)
if not final_state:
return None
path = []
cur = final_state
while cur is not None:
path.append((cur, move_taken[cur]))
cur = parent[cur]
path.reverse()
return path
def print_solution(solution):
if not solution:
print("未找到解法")
return
print("初始状态为 (A, B, C):(10, 0, 0)")
for idx, (state, move) in enumerate(solution):
if move is None:
continue
from_idx, to_idx, amount = move
names = ['A(10两)', 'B(7两)', 'C(3两)']
print(f"第{idx}步:从 {names[from_idx]} 倒 {amount} 两 到 {names[to_idx]},得到状态 {state}")
print("目标状态:A 瓶中正好有 5 两油,实现均分!")
if __name__ == '__main__':
solution = dfs()
print_solution(solution)