#include <iostream>
//#include <windows.h>
#define STEP 20
using namespace std;
int m=0,n=0;/*m为take函数执行次数,n为for循环次数*/
int a[STEP][4];/*0狼 1羊 2菜 3人*/
int b[STEP];
int count = 0;
void disp(int s, int n);
void take(int step);
void farmer() {
int i, j;
for(i = 0; i < STEP; i++) {
b[i] = 0;
for(j = 0; j < 4; j++)
a[i][j] = 0;
}
/*初始化*/
take(0);
}
void disp(int s, int n) {
if(s == 0) {
/*人未过,则过去*/
if(n == 0) cout << "农夫自己过去";
else if(n == 1) cout << "把狼送过去";
else if(n == 2) cout << "把羊送过去";
else if(n == 3) cout << "把蔬菜送过去";
cout << "\n";
} else {
/*人已过,则回来*/
if(n == 0) cout << "农夫自己回来";
else if(n == 1) cout << "把狼送回来";
else if(n == 2) cout << "把羊送回来";
else if(n == 3) cout << "把蔬菜送回来";
cout << "\n";
}
}/*输出*/
void take(int step) {
/*printf("\n%d-%d%d%d%d-%d\t",step+1,a[step][0],a[step][1],a[step][2],a[step][3],++m);*/
int i;
if (a[step][0] + a[step][1] + a[step][2] + a[step][3] == 4) {
count++;
cout << " 第" << count << "种方法:\n";
for(i = 0; i < step; i++) {
cout << "第" << i + 1 << "步骤: ";
disp(a[i][3], b[i] + 1);
}
cout << "\n";
return;
}
/*若成功,则结束*/
for (i = 0; i < step; i++)
if(a[i][0] == a[step][0] && a[i][1] == a[step][1] && a[i][2] == a[step][2] && a[i][3] == a[step][3])
return;/*若重复,则结束,否则无限循环*/
if (a[step][1] != a[step][3] && (a[step][2] == a[step][1] || a[step][0] == a[step][1]))
return;/*若危险,则结束*/
for (i = -1; i <= 2; i++) {
b[step] = i;
a[step + 1][0] = a[step][0];
a[step + 1][1] = a[step][1];
a[step + 1][2] = a[step][2];
a[step + 1][3] = a[step][3];/*下次继承本次状态*/
a[step + 1][3] = 1 - a[step + 1][3];/*农夫动*/
/*printf("%d-%d-%d%d%d%d-%d%d%d%d-%d-%d\t",step+1,i+2,a[step][0],a[step][1],a[step][2],a[step][3],a[step+1][0],a[step+1][1],a[step+1][2],a[step+1][3],++n,m);*/
if (i == -1)/*四种情况:农夫自己过 农夫带狼过 农夫带羊过 农夫带菜过*/
take(step + 1);
else if (a[step][i] == a[step][3]) {
a[step + 1][i] = a[step + 1][3];/*带~过河,则~与农夫初末态相同*/
take(step + 1);
}/*60次*/
/*printf("%d-%d-%d%d%d%d-%d%d%d%d-%d-%d\t",step+1,i+2,a[step][0],a[step][1],a[step][2],a[step][3],a[step+1][0],a[step+1][1],a[step+1][2],a[step+1][3],n,m);*/
}
}
int main() {
farmer();
system("pause");
return 0;
}
原文地址:https://www.cnblogs.com/sha-/p/11047854.html