使用递归!
- import java.util.*;
- class Test_1
- {
- // 三个杯子
- private static int CupA = 8;
- private static int CupB = 5;
- private static int CupC = 3;
- // 保存倒水的状态,不能又重复的,避免死循环
- private static ArrayList<String> history = new ArrayList<String>();
- public static void main(String[] args)
- {
- putWater(8,0,0,"8-0-0");
- }
- public static void putWater(int a, int b, int c, String str)
- {
- // 存在了这种状态了,不能继续,否则死循环
- if(history.contains(str))
- return;
- //System.out.println(str);
- if(a == 4 && b == 4)
- {
- history.add(str);
- System.out.println(history);
- System.out.println("OK");
- return;
- }
-
- history.add(str);
- // 优先填补0容量的杯子,A给B
- if(a != 0 && b == 0)
- {
- int tempa = a + b > CupB ? a + b - CupB : 0;
- int tempb = a + b > CupB ? CupB : a + b;
- putWater(tempa, tempb, c , tempa + "-" + tempb + "-" + c);
- }
- else
- {
- // B给C
- if(b != 0 && c == 0)
- {
- int tempb = b + c > CupC ? b + c - CupC : 0;
- int tempc = b + c > CupC ? CupC : b + c;
- putWater(a, tempb, tempc, a + "-" + tempb + "-" + tempc);
- }
- // A杯倒给B杯
- else if(a == CupA)
- {
- int tempa = a + b > CupB ? a + b - CupB : 0;
- int tempb = a + b > CupB ? CupB : a + b;
- putWater(tempa, tempb, c , tempa + "-" + tempb + "-" + c);
- }
- // B杯倒给C杯
- else if(b == CupB)
- {
- int tempb = b + c > CupC ? b + c - CupC : 0;
- int tempc = b + c > CupC ? CupC : b + c;
- putWater(a, tempb, tempc, a + "-" + tempb + "-" + tempc);
- }
- // C杯倒给A杯
- else if(c == CupC)
- {
- int tempc = c + a > CupA ? c + a - CupA : 0;
- int tempa = c + a > CupA ? CupA : c + a;
- putWater(tempa, b, tempc, tempa + "-" + b + "-" + tempc);
- }
- }
- }
- }
复制代码
|