Java简单实现农夫过河问题示例

时间:2021-11-21 18:25:32

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

一、问题描述

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

二、实现代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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程序设计有所帮助。