|
63楼的题deepseek直接做对了
- from collections import deque
- def water_bucket_bfs():
- # 定义水桶容量
- capacities = (43, 59, 100)
- # 初始状态
- initial_state = (0, 0, 100)
- # 目标状态
- target_state = (0, 50, 50)
- # 使用 BFS 搜索
- queue = deque() # 存储待探索的状态
- queue.append((initial_state, [])) # (当前状态, 路径)
- visited = set() # 存储已访问的状态
- while queue:
- current_state, path = queue.popleft()
- if current_state == target_state:
- # 找到目标状态,输出路径
- return path + [current_state]
- if current_state in visited:
- continue
- visited.add(current_state)
- # 生成所有可能的下一步状态
- a, b, c = current_state
- # 从 3 升桶倒水
- if a > 0:
- # 3 升桶倒入 5 升桶
- pour_amount = min(a, capacities[1] - b)
- new_state = (a - pour_amount, b + pour_amount, c)
- queue.append((new_state, path + [current_state]))
- # 3 升桶倒入 8 升桶
- pour_amount = min(a, capacities[2] - c)
- new_state = (a - pour_amount, b, c + pour_amount)
- queue.append((new_state, path + [current_state]))
- # 从 5 升桶倒水
- if b > 0:
- # 5 升桶倒入 3 升桶
- pour_amount = min(b, capacities[0] - a)
- new_state = (a + pour_amount, b - pour_amount, c)
- queue.append((new_state, path + [current_state]))
- # 5 升桶倒入 8 升桶
- pour_amount = min(b, capacities[2] - c)
- new_state = (a, b - pour_amount, c + pour_amount)
- queue.append((new_state, path + [current_state]))
- # 从 8 升桶倒水
- if c > 0:
- # 8 升桶倒入 3 升桶
- pour_amount = min(c, capacities[0] - a)
- new_state = (a + pour_amount, b, c - pour_amount)
- queue.append((new_state, path + [current_state]))
- # 8 升桶倒入 5 升桶
- pour_amount = min(c, capacities[1] - b)
- new_state = (a, b + pour_amount, c - pour_amount)
- queue.append((new_state, path + [current_state]))
- return None # 如果没有找到解
- # 运行 BFS 搜索
- path = water_bucket_bfs()
- if path:
- print("变化路径:")
- for state in path:
- print(state)
- else:
- print("未找到解。")
复制代码 |
|