黑马程序员技术交流社区

标题: 过河的一个基础测试题,基础不好真的没思路 [打印本页]

作者: 黑色礼服    时间: 2015-7-19 11:01
标题: 过河的一个基础测试题,基础不好真的没思路
  1. /*
  2. 10、 一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。
  3. 当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼,当老农和猫狗鱼在一起时,
  4. 则不会发生这种问题。编程解决猫狗鱼过河问题。*/

  5. import java.util.ArrayList;
  6. import java.util.List;
  7. public class Guohejihe
  8. {
  9.         ArrayList<String> here = new ArrayList<String>();
  10.         ArrayList<String> there = new ArrayList<String>();

  11. //判断集合是否安全的函数
  12. public boolean isSafty(List<String> list)
  13.         {
  14.                 if (list.contains("dog") && list.contains("cat")
  15.                                 || list.contains("cat") && list.contains("fish"))
  16.                 {
  17.                         return false;
  18.                 }
  19.                 return true;
  20.         }

  21. public Guohejihe()
  22. {
  23.         here.add("Dog");
  24.         here.add("cat");
  25.         here.add("fish");
  26. }

  27. //带东西过河的函数
  28. public void toTake()
  29. {
  30.         String str = here.get(0);
  31.         here.remove(str);
  32.         if (isSafty(here))
  33.         {
  34.                 System.out.println("农夫带着" + str + "去对岸,这边还有" + here + ",对岸有" + there);
  35.                 toThere(str);
  36.         }

  37.         else
  38.         {
  39.                 here.add(str);
  40.                 toTake();
  41.         }
  42. }
  43. //将带过去的东西带回来的函数
  44. public void toThere(String s)
  45. {
  46.         if (isSafty(there))
  47.         {
  48.                 there.add(s);
  49.                 if(here.isEmpty())
  50.                 {
  51.                         System.out.println("农夫,"+there+"完成");
  52.                         return;
  53.                 }
  54.                 if(isSafty(there))
  55.                 {
  56.                         System.out.println("农夫回到原地,对岸有" + there);
  57.                         toTake();
  58.                 }
  59.                 else
  60.                 {
  61.                         String temp=there.get(0);
  62.                         there.remove(temp);
  63.                         System.out.println("农夫带着"+temp+"回去,这边有" + here + ",对岸有" + there);
  64.                         here.add(temp);
  65.                         toTake();
  66.                 }
  67.         }

  68.         else
  69.         {
  70.                 there.remove(s);
  71.                 toTake();
  72.         }
  73. }
  74. public static void main(String[] args)
  75.         {
  76.                 new Guohejihe().toTake();
  77.         }
  78. }
复制代码

这个题也是让我醉了,刚看到以为是脑筋急转弯,用代码实现好难想  ,原来用StringBuilder没做出来,直到今天看到集合才有点思路。
作者: gaoming971366    时间: 2015-7-19 11:07
脑筋急转弯这么麻烦,也用代码实现了,学习了
作者: 小丑    时间: 2015-7-19 11:22
看见这种题目人就醉了
作者: a12366456    时间: 2015-7-19 11:43
我觉得题目的意思是让我们编程验证提供的过河思路是否正确,而不是编程得出过河的方案,这样就好想了
作者: xyxlx111    时间: 2015-7-19 22:07
写的不错,顶一个




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2