- //一位老农带着猫、狗、鱼过河,河边有一条船,每次老农只能带一只动物过河。当老农不和猫狗鱼在一起时,狗会咬猫,猫会吃鱼,当老农和猫狗鱼在一起时,则不会发生这种问题。编程解决猫狗鱼过河问题。
- import java.util.ArrayList;
- import java.util.List;
- //先带猫过去,然后回来把狗带过,把猫带回来
- //再把鱼带过去,再回来带猫
- public class Test10
- {
- ArrayList<String> here = new ArrayList<String>();
- ArrayList<String> there = new ArrayList<String>();
- public boolean isSafty(List list)
- {
- if (list.contains("dog") && list.contains("cat")
- || list.contains("cat") && list.contains("fish"))
- {
- return false;
- }
- return true;
- }
-
- public Test10()
- {
- 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("1农夫带着" + 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("2农夫回到原点,对岸有" + there);
- toTake();
- }
- else
- {
- String temp=there.get(0);
- there.remove(temp);
- System.out.println("3农夫带着"+temp+"回到原点,这边有" + here + ",对岸有" + there);
- here.add(temp);
- toTake();
- }
- }
- else
- {
- there.remove(s);
- toTake();
- }
- }
- public static void main(String[] args)
- {
- new Test10().toTake();
- }
- }
复制代码
|