农夫过河问题
来源:互联网 发布:淘宝扣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");}}
- 农夫过河问题实现
- 农夫过河问题
- 农夫过河问题
- 农夫过河问题
- 【人工智能】农夫过河问题
- 农夫过河问题
- 农夫、狼、羊过河问题
- 农夫过河问题的求解
- C语言农夫过河问题
- c实现农夫过河问题
- 农夫过河问题学习笔记
- 农夫过河
- 农夫过河
- 农夫过河
- 农夫过河
- 农夫过河
- Java中关于农夫过河的问题
- 农夫过河问题——程序设计
- JavaScript与 HTML表单的交互过程,想要学习动态网页但是无从下手的新手看看。
- 一款好用的MySql可视化工具HeidiSQL
- 端口号正则表达式
- 11u-boot启动过程分析——基于lpc2210的移植代码
- 介绍几个开源J2ME UI库
- 农夫过河问题
- memcache 编译 安装
- 深入理解C语言小记
- “神棍节”背后的故事
- 指针数组的要运用和运算以及类的简单阐述
- 多个comboBox绑定一个数据源的办法
- jsp
- Linux 的多线程编程的高效开发经验
- vi 命令