农夫有 猫 狗 鱼三个动物,要用船过河,每次运一个动物,狗吃猫,猫吃鱼,要怎么样才能过河呢?通过集合体现
package it.heima.list;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.tree.DefaultTreeCellEditor.EditorContainer;
import javax.xml.stream.events.EntityDeclaration;
public class ListDemo {
ArrayList<String> startList = new ArrayList<>();
ArrayList<String> endList = new ArrayList<>();
public ListDemo() {
startList.add("fish");
startList.add("cat");
startList.add("dog");
}
public static void main(String[] args) {
ListDemo demo=new ListDemo();
demo.toTake();
}
public boolean isSafe(ArrayList<String> list) {
boolean flag = true;
if (list.contains("cat") && list.contains("fish") || list.contains("cat") && list.contains("dog")) {
flag = false;
}
return flag;
}
public boolean isEmpty(ArrayList<String> list) {
return list.isEmpty();
}
public void toTake() {
String animal = startList.get(0);
startList.remove(0);
if (isSafe(startList)) {
toThere(animal);
} else {
startList.add(animal);
toTake();
}
}
public void toThere(String animal) {
endList.add(animal);
System.out.println("农夫带着"+animal+"过河了");
System.out.println("河这边还有"+startList);
System.out.println("过河了的有"+endList);
if(isEmpty(startList)){
System.out.println("动物都过河了");
return;
}
if(isSafe(endList)){
toTake();
}else{
String s=endList.get(0);
endList.remove(0);
if(isSafe(endList)){
System.out.println("农夫带着"+s+"回到了这边");
startList.add(s);
toTake();
}else{
toThere(s);
}
}
}
}
|
|