问题描述
- 关于农夫问题的C语言解决
-
以下代码输出为no solutin.,请问错在哪里?#include<stdio.h> #include<stdlib.h> struct seqqueue { int maxnum; int f,r; int *data; }; int main() { struct seqqueue *createemptyqueue_seq(int m); void enqueue_seq(struct seqqueue *p,int x); void dequeue_seq(struct seqqueue *p); int frontqueue_seq(struct seqqueue *p); int isemptyqueue_seq(struct seqqueue *hq); int farmer(int location); int wolf(int location); int cabbage(int location); int goat(int location); int safe(int location); void farmerproblem(); farmerproblem(); return 0; } struct seqqueue *createemptyqueue_seq(int m) //创建空队列 { struct seqqueue *p=(struct seqqueue*)malloc(sizeof(struct seqqueue)); if(p!=NULL) { p->maxnum=m; p->data=(int*)malloc(sizeof(int)*p->maxnum); if(p->data) { p->f=p->r=0; return p; } else { free(p); } } printf("out of space!"); return NULL; } void enqueue_seq(struct seqqueue *p,int x) //入队 { if((p->r+1)%p->maxnum==p->f) printf("full queue."); else { p->data[p->r]=x; p->r=(p->r+1)%p->maxnum; } } void dequeue_seq(struct seqqueue *p) //出队 { if(p->f==p->r) printf("empty queue!"); else p->f=(p->f+1)%p->maxnum; } int frontqueue_seq(struct seqqueue *p) //取队列的头元素 { if(p->f==p->r) printf("empty queue!"); else return (p->data[p->f]); } int isemptyqueue_seq(struct seqqueue *q) { //判断队首或队尾任一个指针是否为空即可 if(q->r==q->f) { return 1; } else { return 0; } } int farmer(int location) //判断农夫的位置 { return (0!=(location&0x08)); } int wolf(int location) //判断狼的位置 { return (0!=(location&0x04)); } int cabbage(int location) //判断白菜的位置 { return (0!=(location&0x02)); } int goat(int location) //判断羊的位置 { return (0!=(location&0x01)); } int safe(int location) //安全状态判断函数 { if((goat(location)==cabbage(location))&&(goat(location)!=farmer(location))) return 0; if((goat(location)==wolf(location))&&(goat(location)!=farmer(location))) return 0; return 1; } void farmerproblem() { int i,movers,location,newlocation; int route[16]; struct seqqueue *moveto; moveto=createemptyqueue_seq(17); enqueue_seq(moveto,0x00); for(i=0;i<16;i++) route[i]=-1; route[0]=0; while(!isemptyqueue_seq(moveto)&&(route[15]==-1)) { location=frontqueue_seq(moveto); dequeue_seq(moveto); for(movers=1;movers<=8;movers<<=1) if((0!=(location&0x08))==(0!=(location&movers))) { newlocation=location^(0x00|movers); if(safe(newlocation)&&(route[newlocation]==-1)) { route[newlocation]=location; enqueue_seq(moveto,newlocation); } } } if(route[15]!=-1) { printf("the revers path is:n"); for(location=15;location>=0;location=route[location]) { printf("the location is:%dn",location); if(location==0)exit(0); } } else printf("no solution.n"); }
解决方案
这行错了
newlocation=location^(0x00|movers);
修改
newlocation=location^(0x08|movers);
解决方案二:
http://blog.sina.com.cn/s/blog_50d936c40100e2wl.html
解决方案三:
http://blog.csdn.net/jamesjxin/article/details/6891188
解决方案四:
newlocation=location^(0x00|movers);
修改
newlocation=location^(0x08|movers);
时间: 2024-10-27 22:30:03