本文实例讲述了Java简单实现农夫过河问题。分享给大家供大家参考,具体如下:

一、问题描述

老伯伯要带鱼、狗、猫过河到对岸.,有一条船,只能坐一个人,老伯每次只能带一样动物过河,当老伯不在的时侯狗会咬猫,猫会吃鱼.,请问怎么顺序过河呢?

二、实现代码

package demo;
import java.util.ArrayList;
import java.util.List;
public class CrossRiver {
    List<String> listThis = new ArrayList<String>();
    List<String> listThat = new ArrayList<String>();
    /*boolean thisFlag = true;
    boolean thatFlag = false;
*/
    public CrossRiver() {
        listThis.add("dog");
        listThis.add("fish");
        listThis.add("cat");
        // listThis.add("people");
    }
    public boolean isSafe(@SuppressWarnings("rawtypes") List list){
        if(list.contains("fish")&&list.contains("cat")||list.contains("cat")&&list.contains("dog")){
            return false;
        }else{
            return true;
        }
    }
    public void thisTothat(){
        String str = listThis.get(0);
        listThis.remove(str);
        if(this.isSafe(listThis)){
            System.out.println("农夫带着 " + str + " 从此岸到彼岸");
            System.out.println("此岸" + listThis + "\b" + "彼岸" + listThat);
            System.out.println();
            listThat.add(str);
            thatToThis();
        }else{
            listThis.add(str);
            thisTothat();
        }
    }
    public void thatToThis(){
        if(listThis.isEmpty()){
            System.out.println("此岸" + listThis + "\b" + "彼岸" + listThat);
            return;
        }
        if(isSafe(listThat)){
            System.out.println("农夫从彼岸到此岸");
            System.out.println("此岸" + listThis + "\b" + "彼岸" + listThat);
            System.out.println();
            thisTothat();
        }else{
            String str = listThat.get(0);
            listThat.remove(0);
            if(isSafe(listThat)){
                System.out.println("农夫带着 " + str + " 从彼岸到此岸");
                System.out.println("此岸" + listThis + "\b" + "彼岸" + listThat);
                System.out.println();
                listThis.add(str);
                thisTothat();
            }else{
                listThat.add(str);
                thatToThis();
            }
        }
    }
    public static void main(String[] args){
        System.out.println("脚本之家测试结果:");
        System.out.println();
        new CrossRiver().thisTothat();
    }
}

运行结果:

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

01-27 21:12