黑马程序员技术交流社区
标题:
过河的一个基础测试题,基础不好真的没思路
[打印本页]
作者:
黑色礼服
时间:
2015-7-19 11:01
标题:
过河的一个基础测试题,基础不好真的没思路
/*
10、 一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。
当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼,当老农和猫狗鱼在一起时,
则不会发生这种问题。编程解决猫狗鱼过河问题。*/
import java.util.ArrayList;
import java.util.List;
public class Guohejihe
{
ArrayList<String> here = new ArrayList<String>();
ArrayList<String> there = new ArrayList<String>();
//判断集合是否安全的函数
public boolean isSafty(List<String> list)
{
if (list.contains("dog") && list.contains("cat")
|| list.contains("cat") && list.contains("fish"))
{
return false;
}
return true;
}
public Guohejihe()
{
here.add("Dog");
here.add("cat");
here.add("fish");
}
//带东西过河的函数
public void toTake()
{
String str = here.get(0);
here.remove(str);
if (isSafty(here))
{
System.out.println("农夫带着" + str + "去对岸,这边还有" + here + ",对岸有" + there);
toThere(str);
}
else
{
here.add(str);
toTake();
}
}
//将带过去的东西带回来的函数
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("农夫回到原地,对岸有" + there);
toTake();
}
else
{
String temp=there.get(0);
there.remove(temp);
System.out.println("农夫带着"+temp+"回去,这边有" + here + ",对岸有" + there);
here.add(temp);
toTake();
}
}
else
{
there.remove(s);
toTake();
}
}
public static void main(String[] args)
{
new Guohejihe().toTake();
}
}
复制代码
这个题也是让我醉了,刚看到以为是脑筋急转弯,用代码实现好难想 ,原来用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