本帖最后由 香草芭芙 于 2014-10-21 15:44 编辑
- package com.itheima.test;
- import java.util.*;
- public class Test30
- {
- public static void main(String[] args)
- {
- String nong = "农", dog = "狗", cat = "猫", fish = "鱼";
- LinkedList<String> anA = new LinkedList<String>();
- LinkedList<String> anB = new LinkedList<String>();
- anA.addFirst(nong);anA.addFirst(dog);anA.addFirst(cat);anA.addFirst(fish);
- System.out.println("原始状态-这边海岸: " + anA);
- System.out.println("原始状态-那边海岸: " + anB);
- fgx();// ----------------------------------------------------------------------------
- String[] s = new String[1];
- while (anA.size() != 0)
- {
- if (anA.contains(nong))
- {
- if (!isDanger(anB)) // B岸不危险.
- {
- anA2anB(nong, anA, anB);
- s[0] = anA.getFirst();
- anA2anB(s[0], anA, anB);
- System.out.println("农 & " + s[0] + " 去B岸");
- System.out.println("A岸: " + anA);
- System.out.println("B岸: " + anB);
- fgx();// --------
- }
- }
- else if (anB.contains(nong))
- {
- if (isDanger(anA)) // A岸危险.
- {
- System.out.print("A岸危险: ");
- System.out.println(anA.getFirst() + " 与 " + anA.getLast() + " 不和谐, " + "回到上一步");
- reSet(nong, anA, anB);
- reSet(s[0], anA, anB);
- System.out.println("A岸: " + anA);
- System.out.println("B岸: " + anB);
- fgx();// --------
- continue;
- }
- else
- // A岸不危险.
- {
- anB2anA(nong, anB, anA);
- if (isDanger(anB)) // 判断农夫一个人走是否可以?
- {
- System.out.print("农 1个人 走的话岸B危险: ");
- System.out.println(anB.getFirst() + " 与 " + anB.getLast() + " 不和谐");
- s[0] = anB.getFirst();
- anB2anA(s[0], anB, anA);
- System.out.println("所以 农 & " + s[0] + " 去 A岸");
- }
- else
- System.out.println("农 1个人 去 A岸");
- System.out.println("A岸: " + anA);
- System.out.println("B岸: " + anB);
- fgx();// --------
- }
- }
- }
- System.out.println("搬运结束");
- }
- public static void fgx()
- {
- System.out.println("-------------------------------");
- }
- public static boolean anA2anB(String s, LinkedList<String> anA, LinkedList<String> anB)
- {
- if (anA.contains(s))
- {
- anA.remove(s);
- anB.addLast(s);
- return true;
- }
- else
- return false;
- }
- public static boolean anB2anA(String s, LinkedList<String> anB, LinkedList<String> anA)
- {
- if (anB.contains(s))
- {
- anB.remove(s);
- anA.addLast(s);
- return true;
- }
- else
- return false;
- }
- public static void reSet(String s, LinkedList<String> listHere, LinkedList<String> listThere)
- {
- if (listHere.contains(s))
- {
- listHere.remove(s);
- listThere.addLast(s);
- }
- else if (listThere.contains(s))
- {
- listThere.remove(s);
- listHere.addLast(s);
- }
- }
- public static boolean isDanger(LinkedList<String> list)
- {
- if (!list.contains("农"))
- {
- if (list.contains("猫") && list.contains("狗") || list.contains("猫") && list.contains("鱼"))
- return true;
- }
- return false;
- }
- }
复制代码
|