农夫过河问题

来源:互联网 发布:淘宝扣12分 编辑:程序博客网 时间:2024/06/08 17:42

这是《数据结构案例教程》上的,用了位运算,个人认为写的十分巧妙。

#include<stdio.h>#include<stdlib.h>void farmerProblem();#define MAXQSIZE 100typedef int ElemType;typedef struct {ElemType data[MAXQSIZE];int front,rear;}SqQueue;void Init_SqQueue(SqQueue *Q){Q -> front = Q -> rear = 0;}int Empty_SqQueue(SqQueue *Q){return(Q -> rear == Q ->front);}void In_SqQueue(SqQueue *Q,int e){if(Q -> rear == MAXQSIZE){return;}Q -> data[Q -> rear] = e;Q -> rear += 1;}void Out_SqQueue(SqQueue *Q,int *e){if(Q -> rear == Q -> front){return;}*e = Q -> data[Q -> front];Q -> front += 1;}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;}int main(){farmerProblem();getchar();return 0;}void farmerProblem(){int moves,location,newlocation;                   int route[16];int i;SqQueue moveto;//location = 0;Init_SqQueue(&moveto);In_SqQueue(&moveto,0x00);for(i = 0;i < 16;i++){route[i] = -1;}route[0] = 0;while(!Empty_SqQueue(&moveto) && route[15] == -1){Out_SqQueue(&moveto,&location);for(moves = 1;moves <= 8;moves <<=1)            {if(((location & 0x08) != 0) == ((location & moves) != 0))                {newlocation = location ^ (0x08 | moves);                                if(safe(newlocation) && (route[newlocation] == -1)){route[newlocation] = location;In_SqQueue(&moveto,newlocation);}}}}if(route[15] != -1){printf("\n The reverse path is :");for(i =15;i>=0;i=route[i]){printf("\n The location is %d ",i);if(i == 0){break;}}}else{printf("No path");}}