以下代碼輸出為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:%d\n",location);
if(location==0)exit(0);
}
}
else printf("no solution.\n");
}
這行錯了
newlocation=location^(0x00|movers);
修改
newlocation=location^(0x08|movers);