- //思路:先带猫过去,然后回来把狗带过,把猫带回来,再把鱼带过去,再回来带猫.
- public class Test10 {
-
- public static void main(String[] args) {
- new Test10().tohere();
- }
- //创建一个集合,代表起始点.
- ArrayList<String> here = new ArrayList<String>();
- //创建一个集合,代表终点.
- ArrayList<String> there = new ArrayList<String>();
- //添加元素.
- public Test10() {
- here.add("Dog");
- here.add("cat");
- here.add("fish");
- }
- //定义一个方法,用来判断这三个动物之间关系.
- public boolean isSafe(ArrayList<String> al) {
- if (al.contains("dog") && al.contains("cat")
- || al.contains("cat") && al.contains("fish")) {
- return false;
- }
- return true;
- }
- //定义一个方法,将起点的元素送到终点.
- public void tohere() {
- String str = here.get(0);
- here.remove(str);
- if (isSafe(here)) {
- System.out.println("1农夫带着" + str + "去往对岸,这边还剩下" + here + ",对岸有"
- + there);
- toThere(str);
- } else {
- here.add(str);
- tohere();
- }
- }
- //定义一个方法,用来查看终点的元素.
- public void toThere(String s) {
-
- if (isSafe(there)) {
- there.add(s);
- if(here.isEmpty()){
- System.out.println("4农夫,"+there+"都被你带过来了");
- return;
- }
- if(isSafe(there)){
- System.out.println("2农夫回到原点,对岸有" + there);
- tohere();
- }else{
- String temp=there.get(0);
- there.remove(temp);
- System.out.println("3农夫带着"+temp+"回到原点,这边有" + here + ",对岸有" + there);
- here.add(temp);
- tohere();
- }
- } else {
- there.remove(s);
- tohere();}
- }
- }
复制代码
这是基础测试题吧!我也做了这道题!你借鉴借鉴吧! |