怎么感觉好几个地方都瞅着那么眼熟呢?
- import java.util.ArrayList;
- public class Crossing {
- public static void main(String[] args) {
- ArrayList<Animal> riverBank = new ArrayList<Animal>();
- ArrayList<Animal> oppositeBank = new ArrayList<Animal>();
- new RiverCrossing(new AddPet().pet(riverBank), oppositeBank).riverCrossing();
- for(Animal pet : oppositeBank){
- System.out.println(pet.getName());
- }
- }
- }
- class AddPet{
- public ArrayList<Animal> pet(ArrayList<Animal> riverBank) {
- riverBank.add(new Animal("狗", "猫"));
- riverBank.add(new Animal("猫", "狗"));
- riverBank.add(new Animal("鱼", "猫"));
- return riverBank;
- }
- }
- class RiverCrossing{
- private ArrayList<Animal> riverBank = null;
- private ArrayList<Animal> oppositeBank = null;
- private ArrayList<Animal> temp = new ArrayList<Animal>();
- public RiverCrossing(ArrayList<Animal> riverBank,ArrayList<Animal> oppositeBank) {
- this.riverBank = riverBank;
- this.oppositeBank = oppositeBank;
- this.temp.addAll(this.riverBank);
- }
- private void initialization() {
- riverBank.clear();
- oppositeBank.clear();
- this.riverBank.addAll(temp);
- }
- public void riverCrossing() {
- move(oppositeBank,riverBank,0);
- int count = 0;
- while (true){
- if (riverBank.size() == 2){
- count++;
- if (riverBank.get(0).getEnemy().equals(riverBank.get(1).getName()) || riverBank.get(1).getEnemy().equals(riverBank.get(0).getName())){
- if ((riverBank.get(0).isFlag() == riverBank.get(1).isFlag()) && !riverBank.get(0).isFlag()){
- initialization();
- move(oppositeBank,riverBank,count);
- } else{
- move(oppositeBank,riverBank,0);
- }
- } else{
- riverBank.get(0).setFlag(true);
- riverBank.get(1).setFlag(true);
- move(oppositeBank,riverBank,1);
- }
- } else{
- if (oppositeBank.size() == 2){
- if ((oppositeBank.get(0).getEnemy().equals(oppositeBank.get(1).getName())|| oppositeBank.get(1).getEnemy().equals(oppositeBank.get(0).getName())) && (oppositeBank.get(0).isFlag() != oppositeBank.get(1).isFlag())){
- move(riverBank,oppositeBank,0);
- }
- else{
- if ((oppositeBank.get(0).isFlag() == oppositeBank.get(1).isFlag()) && oppositeBank.get(0).isFlag()) {
- move(oppositeBank,riverBank,0);
- System.out.println("河岸有" + riverBank.size() + "只动物");
- System.out.println("对岸有" + oppositeBank.size() + "只动物");
- System.out.println("过河结束");
- break;
- }
- }
- }
- }
- }
- }
- private void move(ArrayList<Animal> cross,ArrayList<Animal> clear,int index){
- cross.add(clear.remove(index));
- }
- }
- class Animal {
- private String name;
- private String enemy;
- private boolean flag = false;
- public Animal(String name, String enemy) {
- this.name = name;
- this.enemy = enemy;
- }
- public String getName() {
- return name;
- }
- public String getEnemy() {
- return enemy;
- }
- public boolean isFlag() {
- return flag;
- }
- public void setFlag(boolean flag) {
- this.flag = flag;
- }
- }
复制代码 |