import java.util.ArrayList; public class DaoYou { public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<State> stateList = new ArrayList<State>(); Tong t1 = new Tong("5斤桶",5,0); Tong t2 = new Tong("8斤桶",8,0); Tong t3 = new Tong("12斤桶",12,12); DaoYou dy = new DaoYou(); State st = new State(t1,t2,t3,0,0); stateList.add(st); try { dy.dao(st, stateList); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i=0; i< stateList.size(); i++){ System.out.println(stateList.get(i)); } } public boolean dao(State s,ArrayList<State> states) throws CloneNotSupportedException{ Tong tempT1 = (Tong)s.getT1().clone(); Tong tempT2 = (Tong)s.getT2().clone(); Tong tempT3 = (Tong)s.getT3().clone(); //t1 向 t2 里边倒油 //还可以对倒油的方法单独拿出来,减少代码的冗余 if(tempT1.getNow() > 0 && tempT2.getNow()<tempT2.getMax()){ Tong t1 = (Tong)tempT1.clone(); Tong t2 = (Tong)tempT2.clone(); Tong t3 = (Tong)tempT3.clone(); int temp = (tempT1.getNow() > tempT2.getMax() - tempT2.getNow()) ? tempT2.getMax() - tempT2.getNow() : tempT1.getNow(); t1.setNow(t1.getNow() - temp); t2.setNow(t2.getNow() + temp); State.NEWID = State.NEWID + 1; State st = new State(t1,t2,t3,State.NEWID,s.getId()); if (states.contains(st)){ State.NEWID = State.NEWID - 1; State tempState = states.get(states.indexOf(st)); if (s.getId() < tempState.getId()){ System.out.println("======向前的捷径倒油方法======"+ states.indexOf(st) + "\t" + s + "\t" + states.get(states.indexOf(st))); }else { System.out.println("============"+ states.indexOf(st) + "\t" + s + "\t" + states.get(states.indexOf(st))); } }else { states.add(st); // 如果倒油成功,返回 // if(t1.getNow() == 6 || t2.getNow() == 6 || t3.getNow() == 6){ // return true; // } dao(st,states); } } //t2向t1里倒油 if(tempT2.getNow() > 0 && tempT1.getNow()<tempT1.getMax()){ Tong t1 = (Tong)tempT1.clone(); Tong t2 = (Tong)tempT2.clone(); Tong t3 = (Tong)tempT3.clone(); int temp = (tempT2.getNow() > tempT1.getMax() - tempT1.getNow()) ? tempT1.getMax() - tempT1.getNow() : tempT2.getNow(); t2.setNow(t2.getNow() - temp); t1.setNow(t1.getNow() + temp); State.NEWID = State.NEWID + 1; State st = new State(t1,t2,t3,State.NEWID,s.getId()); if (states.contains(st)){ State.NEWID = State.NEWID - 1; State tempState = states.get(states.indexOf(st)); if (s.getId() < tempState.getId()){ System.out.println("======向前的捷径倒油方法======"+ states.indexOf(st) + "\t" + s + "\t" + states.get(states.indexOf(st))); }else { System.out.println("============"+ states.indexOf(st) + "\t" + s + "\t" + states.get(states.indexOf(st))); } }else { states.add(st); // 如果倒油成功,返回 // if(t1.getNow() == 6 || t2.getNow() == 6 || t3.getNow() == 6){ // return true; // } dao(st,states); } } |