1、/ farmerProblem.c/ 用队列解决农夫过河问题#include #include typedef int DataType;/顺序队列:类型和界面函数声明struct SeqQueue/ 顺序队列类型定义int MAXNUM; / 队列中最大元素个数int f, r;DataType *q;typedef struct SeqQueue *PSeqQueue; / 顺序队列类型的指针类型PSeqQueue createEmptyQueue_seq(int m)/创建一个空队列PSeqQueue queue = (PSeqQueue)malloc(sizeof(struct Seq
2、Queue);if (queue != NULL)queue-q = (DataType*)malloc(sizeof(DataType) *m);if (queue-q)queue-MAXNUM = m;queue-f = 0;queue-r = 0;return (queue);elsefree(queue);printf(“Out of space!n“); / 存储分配失败return NULL;int isEmptyQueue_seq(PSeqQueue queue)/判断队列是否为空return (queue-f = queue-r);void enQueue_seq(PSeqQu
3、eue queue, DataType x)/ 在队尾插入元素 xif (queue-r + 1) % queue-MAXNUM = queue-f)printf(“Full queue.n“);elsequeue-qqueue-r = x;queue-r = (queue-r + 1) % queue-MAXNUM;void deQueue_seq(PSeqQueue queue)/ 删除队列头部元素if (queue-f = queue-r)printf(“Empty Queue.n“);elsequeue-f = (queue-f + 1) % queue-MAXNUM;DataType
4、 frontQueue_seq(PSeqQueue queue)if (queue-f = queue-r)printf(“Empty Queue.n“);elsereturn (queue-qqueue-f);/个体状态判断函数int farmer(int location)/判断农夫的位置return (0 != (location int wolf(int location)/判断狼的位置return (0 != (location int cabbage(int location)/判断白菜的位置return (0 != (location int goat(int location)
5、/判断羊的位置return (0 != (location /安全状态的判断函数int safe(int location)/ 若状态安全则返回 trueif (goat(location) = cabbage(location) / 羊吃白菜if (goat(location) = wolf(location) / 狼吃羊return (1); / 其他状态是安全的main()int i, movers, location, newlocation;int route16; /用于记录已考虑的状态路径PSeqQueue moveTo; /用于记录可以安全到达的中间状态moveTo = createEmptyQueue_seq(20); /创建空队列enQueue_seq(moveTo, 0x00); /初始状态进队列for (i = 0; i = 0; location = routelocation)printf(“The location is : %dn“, location);if (location = 0)exit(0);elseprintf(“No solution.n“);/问题无解