public class Test10 {
int farmer,cat,dog,fish; //刚开始都为0,也就是都在河的这岸
String type = ""; //记录农夫上一步带的是什么,防止出现死循环,当农夫自己走时type不改变
String isnull = "";//当农夫自己走时,isnull会记录下来,防止出现死循环。
boolean boo = false;
public static void main(String[] args) {
Test10 test = new Test10();
int x = 1;//记录移动的数次
while(true){
test.move();
System.out.println("第"+x+"步");
System.out.println("河这岸有:"+test.print(0));
System.out.println("河对岸有:"+test.print(1));
x++;
//当把全部东西都移动到对岸时,即可停止移动。
if(test.farmer==1&&test.cat==1&&test.dog==1&&test.fish==1){
break;
}
}
}
//农夫过河时需要判断能带什么不能带什么
public void move(){
if(farmer==0){
if(cat==0){
if(!type.equals("cat")){
farmer = 1;
cat = 1;
if(isSafe()){
type = "cat";
return;
}else{
farmer = 0;
cat = 0;
}
}
}
if(dog==0){
if(!type.equals("dog")){
farmer = 1;
dog = 1;
if(isSafe()){
type = "dog";
return;
}else{
farmer = 0;
dog = 0;
}
}
}
if(fish==0){
if(!type.equals("fish")){
farmer = 1;
fish = 1;
if(isSafe()){
type = "fish";
return;
}else{
farmer = 0;
fish = 0;
}
}
}
farmer = 1;
}else if(farmer==1){
//当人在河对岸时需要优先考虑自已到这岸来,从而把东西带到对岸。
if(isnull != "farmer"){
farmer = 0;
isnull = "farmer";
if(isSafe()){
return;
}else{
farmer = 1;
}
}
if(cat==1){
if(!type.equals("cat")){
farmer = 0;
cat = 0;
if(isSafe()){
type = "cat";
isnull = "";
return;
}else{
farmer = 1;
cat = 1;
}
}
}
if(dog==1){
if(!type.equals("dog")){
farmer = 0;
dog = 0;
if(isSafe()){
type = "dog";
isnull = "";
return;
}else{
farmer = 1;
dog = 1;
}
}
}
if(fish==1){
if(!type.equals("fish")){
farmer = 0;
dog = 0;
if(isSafe()){
type = "fish";
isnull = "";
return;
}else{
farmer = 1;
fish = 1;
}
}
}
}
}
//判断现在的状态是否有冲突
public boolean isSafe(){
if(farmer==1){
if(cat==0&&fish==0)return false;
if(cat==0&&dog==0)return false;
}else if(farmer==0){
if(cat==1&&fish==1)return false;
if(cat==1&&dog==1)return false;
}
return true;
}
//打印现在河的两岸都有什么
public String print(int i){
if(i==0){
String str = "";
if(farmer==0)str += "农夫 ";
if(dog==0)str += "狗 ";
if(cat==0)str += "猫 ";
if(fish==0)str += "鱼 ";
return str;
}else if(i==1){
String str = "";
if(farmer==1)str += "农夫 ";
if(dog==1)str += "狗 ";
if(cat==1)str += "猫 ";
if(fish==1)str += "鱼 ";
return str;
}
return null;
}
} |