猴子摘香蕉问题C语言实战教程:人工智能搜索算法详解
猴子、箱子与香蕉——这一经典AI规划问题,是计算机科学领域广泛教授的入门案例。场景设定为:房间内有一只猴子、一个可移动的箱子和悬于天花板的香蕉。用户输入初始位置,系统目标状态为猴子站上箱子并成功摘取香蕉。整个求解过程涉及四个基本动作:移动至箱子处、将箱子推至香蕉正下方、爬上箱子、摘取香蕉。
直观的规划流程背后,实现核心在于状态的高效记录与迭代更新。我们采用一个结构体存储猴子、箱子和香蕉的三维坐标,辅以两个布尔标识:猴子是否已登箱、香蕉是否已被摘取。每个动作封装为一个独立函数,依次执行并修改状态,直至匹配目标条件。
具体实现思路如下:用户以字符串形式输入三个位置标识(例如A、B、C),程序从初始状态出发,顺序调用四个核心函数:
- go_to_box:控制猴子移动到箱子当前位置
- move_box:驱使猴子将箱子推移至香蕉所在坐标
- climb_box:猴子攀爬至箱顶
- get_banana:猴子伸手摘取香蕉
每个函数在执行前均校验当前状态是否满足动作前提,若满足则更新结构体对应字段,并打印当前操作日志。
以下是完整的C++实现源码(注意:代码语言标注为“JavaScript”,实际为C++语法,此处保持原格式):
代码语言:JavaScript(实际为C++)
复制代码
#include
#include
#include
using namespace std;
/*
文件:monkey_get_banana
日期:11.15
*/
struct stack { string MONKEY; string BANANA; string BOX; int HAVE; // 1: banana obtained, 0: not int IS_ON; // 1: monkey on box, 0: not };
bool go_to_box(struct stack& s, string m, string n); bool move_box(struct stack& s, string m, string n); bool climb_box(struct stack& s, string pos); bool get_banana(struct stack& s, string pos);
int main() { string monkey, banana, box; struct stack sq;
cout > monkey >> banana >> box; cout < endl;
// Initialize state sq.MONKEY = monkey; sq.BANANA = banana; sq.BOX = box; sq.HAVE = 0; sq.IS_ON = 0;
// Execute four steps sequentially go_to_box(sq, sq.MONKEY, sq.BOX); move_box(sq, sq.BOX, sq.BANANA); climb_box(sq, sq.BANANA); get_banana(sq, sq.BANANA);
return 0; }
// Function implementations omitted (see full source for details)
程序执行后的输出结果见下图:
上述代码完整实现了作业要求的所有功能!

