【题目取自CSDN-671coder】
第五题:分红酒
题目描述:
有4个红酒瓶子,它们的容量分别是:9升, 7升, 4升, 2升
开始的状态是 [9,0,0,0],也就是说:第一个瓶子满着,其它的都空着。
允许把酒从一个瓶子倒入另一个瓶子,但只能把一个瓶子倒满或把一个瓶子倒空,不能有中间状态。这样的一次倒酒动作称为1次操作。
假设瓶子的容量和初始状态不变,对于给定的目标状态,至少需要多少次操作才能实现?
本题就是要求你编程实现最小操作次数的计算。
输入:最终状态(逗号分隔)
输出:最小操作次数(如无法实现,则输出-1)
例如:
输入:
9,0,0,0
应该输出:
0
输入:
6,0,0,3
应该输出:
-1
输入:
7,2,0,0
应该输出:
2
开始的状态是 [9,0,0,0],也就是说:第一个瓶子满着,其它的都空着。
允许把酒从一个瓶子倒入另一个瓶子,但只能把一个瓶子倒满或把一个瓶子倒空,不能有中间状态。这样的一次倒酒动作称为1次操作。
假设瓶子的容量和初始状态不变,对于给定的目标状态,至少需要多少次操作才能实现?
本题就是要求你编程实现最小操作次数的计算。
输入:最终状态(逗号分隔)
输出:最小操作次数(如无法实现,则输出-1)
例如:
输入:
9,0,0,0
应该输出:
0
输入:
6,0,0,3
应该输出:
-1
输入:
7,2,0,0
应该输出:
2
样例输入:
2 4 1 2
3 1 3 2
2 6 1 0
2 6 1 0
样例输出:
6
9
7
9
7
得分:
3组测试数据 正确个数*10.333 满分31
分析:
一直都在写DFS的题目,BFS写的比较少,很明显总体架构就是BFS了。
9000设定为0次操作,然后广度优先搜,将一次操作之后可能的情况再次放入queue,然后取head再次BFS
JAVA的Queue还好会自动扩容,如果是C可能就麻烦很多
另开一个Queue记录操作次数,每次插入tail的时候就将正在BFS过程中情况的操作次数+1塞入操作次数的Queue
每次同步取情况Queue和操作次数Queue
循环如果搜索到EndCondition则输出
或者完全循环直到Queue.isEmpty()成立说明无法找到对应EndCondition则输出-1表示无法找到
【写了三四个小时的程序,BFS实在不熟练,可能程序各方面不够完美。