黑马程序员-10.一位老农带着猫、狗、鱼过河

来源:互联网 发布:chmod linux 编辑:程序博客网 时间:2024/05/03 14:44
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

    题目是10、 一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼,当老农和猫狗鱼在一起时,则不会发生这种问题。编程解决猫狗鱼过河问题。

    刚接触JAVA,这个问题一开始还是有些难度的,想了很久,在这里说一下我解题的思路,跟大家分享一下。

package com.itheima;import java.util.LinkedList;/** * 10、 一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼, * 当老农和猫狗鱼在一起时,则不会发生这种问题。编程解决猫狗鱼过河问题。 *  * 答:河左岸有农夫,鱼,狗,猫。 * 因为农夫的目的就是要把动物全给带到河右岸,所以分两种情况; * 第一种情况是:当农夫在河左岸时,必须要带一个动物过河右岸,如果农夫把该动物带走,河左岸和谐的话,则计数一次 * 第二种情况是:当农夫在河右岸时,农夫优先选择是自己独自回到河左岸,如果农夫独自回去,河右岸不和谐时,再进行选择带走一个最先进入河右岸的动物。不能选择农夫刚刚才带过来的动物。 *  * @author liwensi * */public class Test10 {public static void main(String[] args) {new River().river();}}class River {LinkedList<String> here = new LinkedList<String> ();LinkedList<String> there = new LinkedList<String> ();String farmer = "老农",cat = "猫",fish = "鱼",dog = "狗";int count = 0;public void river() {here.addLast(farmer);here.addLast(cat);here.addLast(fish);here.addLast(dog);//如果河的左岸有动物,则根据老农所处的位置判断如何过河while(!here.isEmpty()) {//如果老农在河左岸,则需要运行老农在河左岸的过河方法if(here.contains(farmer))hereRiver();elsethereRiver();}System.out.println("在河的右岸有"+there);}//老农在河左岸时的过河方法private void hereRiver() {//老农在河左岸带着其中一种动物过河,这时只需要判断这边的关系是否和谐,//先取老农here.remove(farmer);String animal = null;//老农取一种动物while((animal = here.remove()) != null) {//如果这边是和谐的,就让老农带着这种动物过河的右岸if(isHarmony(here)) {there.addLast(farmer);there.addLast(animal);System.out.println("第"+(++count)+"次:老农带着("+animal+")划船过河的右岸");return ;} else {here.addLast(animal);}}}//老农在河右岸时过河的方法private void thereRiver() {//老农在河右岸上,优先选择是什么都不带的回去there.remove(farmer);String animal = null;//判断河右岸是否和谐,和谐,老农才能什么都不带的回去if(isHarmony(there)){System.out.println("第"+(++count)+"次:老农[什么都不带]划船回到河的左岸");here.addLast(farmer);} else {while((animal = there.remove()) != null) {//老农带走最早进入河右岸的动物,如果这边和谐的话,则带走。if(isHarmony(there)) {here.addLast(farmer);here.addLast(animal);System.out.println("第"+(++count)+"次:老农带着("+animal+")划船回到河的左岸");return ;}else {//如果带走的动物,会导致河右岸不和谐,则不带走该动物。there.addLast(animal);}}}}private boolean isHarmony(LinkedList<String> list) {//判断关系,狗跟猫同时在,或者猫跟鱼同时在的话,则返回false,不和谐if (list.contains(dog) && list.contains(cat)) { return false;}else if(list.contains(cat) && list.contains(fish))  {return false;}else//没有不和谐的条件,返回此地为和谐状态。return true;}}


0 0