A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 1126634865 中级黑马   /  2015-10-16 00:55  /  454 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package com.itheima;

import java.util.ArrayList;
import java.util.*;
/***
* 一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。
* 当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼,
* 当老农和猫狗鱼在一起时,则不会发生这种问题。编程解决猫狗鱼过河问题。
* @author alex
*先带猫过去,然后回来把狗带过,把猫带回来,再把鱼带过去,再回来带猫;
*/

public class Test10 {
        //定义俩集合表示两河岸
        ArrayList<String> here = new ArrayList<String>();
        ArrayList<String> there = new ArrayList<String>();
       
    //判断猫狗鱼在一起时,狗会咬猫,猫会吃鱼
        public boolean isSafty(List list) {
                if (list.contains("dog") && list.contains("cat")
                                || list.contains("cat") && list.contains("fish")) {
                        return false;
                }
                return true;
        }
    //河岸有猫狗鱼
        public Test10() {
                here.add("Dog");
                here.add("cat");
                here.add("fish");
        }
     /***
      * 实现类toTake()
      * 当带走一个动物时,河岸here移除一个动物
      */
        public void toTake() {
                String str = here.get(0);
                here.remove(str);
                if (isSafty(here)) {
                        System.out.println("1农夫带着" + str + "去往对岸,这边还剩下" + here + ",对岸有"
                                        + there);
                        toThere(str);
                } else {
                        here.add(str);
                        toTake();
                }
        }
     /***
      * 实现类toThere()
      * 对岸,来一个动物存一个动物,走一个移除一个,直到河岸没有动物
      * @param s
      */
        public void toThere(String s) {
               
                if (isSafty(there)) {
                        there.add(s);
                        if(here.isEmpty()){
                                System.out.println("农夫,"+there+"都被你带过来了");
                                return;
                        }
                        if(isSafty(there)){
                                System.out.println("2农夫回到原点,对岸有" + there);
                                toTake();
                        }else{
                                String temp=there.get(0);
                                there.remove(temp);
                                System.out.println("3农夫带着"+temp+"回到原点,这边有" + here + ",对岸有" + there);
                                here.add(temp);
                                toTake();
                        }
                } else {
                        there.remove(s);
                        toTake();
                }
        }

        public static void main(String[] args) {
                new Test10().toTake();
        }
}

4 个回复

倒序浏览
经典案例!!!
回复 使用道具 举报
好高级,好复杂...
回复 使用道具 举报

谢谢同学!
回复 使用道具 举报
ageof 发表于 2015-10-16 22:43
好高级,好复杂...

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马