黑马程序员技术交流社区
标题:
【记录】代码练习-猫狗鱼过河案例
[打印本页]
作者:
Kevin.Kang
时间:
2015-8-4 13:18
标题:
【记录】代码练习-猫狗鱼过河案例
本帖最后由 Kevin.Kang 于 2015-8-4 13:22 编辑
* 第十题:一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。
* 当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼,当老农和猫狗鱼在一起时,则不会发生这种问题。
* 编程解决猫狗鱼过河问题。
本来想法是在网上随便找一个抄一下,找到的都不怎么满意,索性就按照自己的想法,结合网上找的代码,重新优化写出了一个比较简洁直观的程序。
package com.itheima;
/*
* 第十题:一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。
* 当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼,当老农和猫狗鱼在一起时,则不会发生这种问题。
* 编程解决猫狗鱼过河问题。
*/
import java.util.ArrayList;
public class Test10 {
// 创建一个集合,代表起点.
public static ArrayList<String> here = new ArrayList<String>();
// 创建一个集合,代表终点.
public static ArrayList<String> there = new ArrayList<String>();
public static void main(String[] args) {
// 添加元素.
here.add("Dog");
here.add("cat");
here.add("fish");
take();
}
// 定义一个方法,用来判断这三个动物之间关系
public static boolean safe(ArrayList<String> al) {
// 当猫狗,猫鱼在一起的时候是不安全的
if (al.contains("dog") && al.contains("cat") || al.contains("cat")
&& al.contains("fish")) {
return false;
}
return true;
}
// 定义一个方法,将起点的动物送到终点
public static void take() {
// 得到一个动物
String s = here.get(0);
// 在起点删除此动物
here.remove(s);
// 判断起点剩下动物关系是否安全
if (safe(here)) {
// 添加此动物到终点中
there.add(s);
System.out.println("带着" + s + "\t去往终点。起点有" + here + ",终点有" + there);
// 判断终点动物关系是否安全
thereSafe();
} else {
// 动物关系不安全就不带此动物,重新来一次。第一次只能带猫去对面
here.add(s);
take();
}
}
// 判断终点的元素
public static void thereSafe() {
// 如果起点没有动物存在,就结束语句。
if (here.isEmpty()) {
System.out.println(there + "都安全过河了");
return;
}
// 终点安全就接着去起点带动物
if (safe(there)) {
take();
} else {
// 不安全就将终点原先动物带回起点
String temp = there.get(0);
there.remove(temp);
here.add(temp);
System.out.println("带着" + temp + "\t回到起点。起点有" + here + ",终点有"
+ there);
take();
}
}
}
复制代码
作者:
王连正
时间:
2015-8-4 17:18
楼主逻辑太强了,我等佩服
作者:
aa233192133
时间:
2015-8-4 20:44
楼主又见你了 我是群里的
作者:
时光游戏
时间:
2015-8-4 20:54
不错,赞一个!
作者:
zhaoyue
时间:
2015-8-4 21:36
我很久之前看到这题了 看的都是集合方法,这两天学到集合,还是没头绪啊,不过看看你的 。佩服。。
作者:
墨琰
时间:
2015-8-4 22:25
楼主强,佩服
作者:
风刃
时间:
2016-3-22 23:53
好6,终于有点头绪了
作者:
Lingxin
时间:
2016-3-23 00:37
顶...顶....顶
作者:
little_bear123
时间:
2016-3-23 10:08
这个问题最好不用编程解决
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2