本帖最后由 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();
- }
- }
- }
复制代码
|
|