农夫过河文档.doc

上传人:cl****1 文档编号:563360715 上传时间:2022-09-27 格式:DOC 页数:7 大小:39.01KB
返回 下载 相关 举报
农夫过河文档.doc_第1页
第1页 / 共7页
农夫过河文档.doc_第2页
第2页 / 共7页
农夫过河文档.doc_第3页
第3页 / 共7页
农夫过河文档.doc_第4页
第4页 / 共7页
农夫过河文档.doc_第5页
第5页 / 共7页
点击查看更多>>
资源描述

《农夫过河文档.doc》由会员分享,可在线阅读,更多相关《农夫过河文档.doc(7页珍藏版)》请在金锄头文库上搜索。

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(stru

2、ct SeqQueue); if (queue != NULL) queue-q = (DataType*)malloc(sizeof(DataType) *m); if (queue-q) queue-MAXNUM = m; queue-f = 0; queue-r = 0; return (queue); else free(queue); printf(Out of space!n); / 存储分配失败 return NULL;int isEmptyQueue_seq(PSeqQueue queue) /判断队列是否为空 return (queue-f = queue-r);void e

3、nQueue_seq(PSeqQueue queue, DataType x)/ 在队尾插入元素x if (queue-r + 1) % queue-MAXNUM = queue-f) printf(Full queue.n); else queue-qqueue-r = x; queue-r = (queue-r + 1) % queue-MAXNUM; void deQueue_seq(PSeqQueue queue)/ 删除队列头部元素 if (queue-f = queue-r) printf(Empty Queue.n); else queue-f = (queue-f + 1) %

4、 queue-MAXNUM;DataType frontQueue_seq(PSeqQueue queue) if (queue-f = queue-r) printf(Empty Queue.n); else return (queue-qqueue-f);/个体状态判断函数int farmer(int location) /判断农夫的位置 return (0 != (location &0x08);int wolf(int location) /判断狼的位置 return (0 != (location &0x04);int cabbage(int location) /判断白菜的位置 r

5、eturn (0 != (location &0x02);int goat(int location) /判断羊的位置 return (0 != (location &0x01);/安全状态的判断函数int safe(int location) / 若状态安全则返回true if (goat(location) = cabbage(location) & (goat(location) != farmer (location) return (0); / 羊吃白菜 if (goat(location) = wolf(location) & (goat(location) != farmer (

6、location) return (0); / 狼吃羊 return (1); / 其他状态是安全的main() int i, movers, location, newlocation; int route16; /用于记录已考虑的状态路径 PSeqQueue moveTo; /用于记录可以安全到达的中间状态 moveTo = createEmptyQueue_seq(20); /创建空队列 enQueue_seq(moveTo, 0x00); /初始状态进队列 for (i = 0; i 16; i+) routei = - 1; /准备数组route初值 route0 = 0; while (!isEmptyQueue_seq(moveTo) & (route15 = - 1) location = frontQueue_seq(moveTo); /取队头状态为当前状态 deQueue_seq(moveTo); for (movers = 1; movers = 8; movers = 0; location = routelocation) printf(The location is : %dn, location); if (location = 0) exit(0); else printf(No solution.n); /问题无解

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 生活休闲 > 社会民生

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号