【文件属性】:
文件名称:农夫过河问题
文件大小:4KB
文件格式:C
更新时间:2017-06-30 08:55:37
农夫过河
数据结构,农夫过河。详细讲述过河
#include
//0代表在河的这边;1代表在河的对岸
struct Condition{
int farmer;
int wolf;
int sheep;
int cabbage;
};
struct Condition conditions[100];//结构体条件数组
char * action [100];
void takeWolfOver(int i)
//把狼来过去
{
action[i]="把狼过去.---->对岸";
conditions[i+1].wolf=1;
conditions[i+1].sheep=conditions[i].sheep;
conditions[i+1].cabbage=conditions[i].cabbage;
}
void takeWolfBack(int i)/*把狼带回来*/
{
action[i]="带狼回来.本岸<---(wolf)";
conditions[i+1].wolf=0;
conditions[i+1].sheep=conditions[i].sheep;
conditions[i+1].cabbage=conditions[i].cabbage;
}
void takeSheepOver(int i)/*把羊带过去*/
{
action[i]="带羊过去.(sheep)--->对岸";
conditions[i+1].wolf=conditions[i].wolf;
conditions[i+1].sheep=1;
conditions[i+1].cabbage=conditions[i].cabbage;
}
void takeSheepBack(int i)/*把羊带回来*/
{
action[i]="带羊回来.本岸<---(sheep)";
conditions[i+1].wolf=conditions[i].wolf;
conditions[i+1].sheep=0;
conditions[i+1].cabbage=conditions[i].cabbage;
}
void takeCabbageOver(int i)/*把菜带过去*/
{
action[i]="带菜过去.(cabbage)--->对岸";
conditions[i+1].wolf=conditions[i].wolf;
conditions[i+1].sheep=conditions[i].sheep;
conditions[i+1].cabbage=1;
}
void takeCabbageBack(int i)/*把菜带回来*/
{
action[i]="带菜回来.本岸<---(cabbage)";
conditions[i+1].wolf=conditions[i].wolf;
conditions[i+1].sheep=conditions[i].sheep;
conditions[i+1].cabbage=0;
}
void getOverBarely(int i)/*过河时的情况*/
{
action[i]="空手过去.(barely)--->对岸";
conditions[i+1].wolf=conditions[i].wolf;
conditions[i+1].sheep=conditions[i].sheep;
conditions[i+1].cabbage=conditions[i].cabbage;/*全不动*/
}
void getBackBarely(int i)/*返回时的情况*/
{
action[i]="空手回来.本岸<---(barely)";
conditions[i+1].wolf=conditions[i].wolf;
conditions[i+1].sheep=conditions[i].sheep;
conditions[i+1].cabbage=conditions[i].cabbage;
}
void showSolution(int i)/*显示解决方法*/
{
int c;
printf("\n");
printf("%s\n","解决办法:");
for(c=0;c=100)/*检查循环是否出现问题*/
{
printf("%s\n","渡河步骤达到100步出错");
return;
}
if(conditions[i].farmer==1&&conditions[i].wolf==1&&conditions[i].sheep==1&&conditions[i].cabbage==1)/*检查是否都过河*/
{
showSolution(i);/*是的,都过河了.返回*/
return;
}
if((conditions[i].farmer!=conditions[i].wolf&&conditions[i].wolf==conditions[i].sheep)||(conditions[i].farmer!=conditions[i].sheep&&conditions[i].sheep==conditions[i].cabbage))/*检查是否丢失,出错*/
{
/*不,狼会吃掉羊,或者羊会吃掉菜的*/
return;
}
/*检查条件是否满足*/
for(c=0;c