1.
node *pre;
用前向链表存储上一位的状态
2.
q.push(node(a1, b1, &Node[cnt], i, t.step + 1));
要用已经定了位置的作为地址,不要用临时变量的地址,临时变量的地址检索不到,会出错。
#include <iostream>
#include <queue>
#include <cstdio>
#include <map>
#include <cstring>
#include <stack>
#include <string>
using namespace std;
struct node
{
int x, y;
node *pre;
int op;
int step;
node(){}
node(int xx, int yy, node *p, int oo, int ss)
{
x = xx;
y = yy;
pre = p;
op = oo;
step = ss;
}
};
int a, b, c;
int cnt;
int vis[200][200];
queue<node> q;
node Node[10010];
stack<int> s;
void outP(node t)
{
node t1 = t;
printf ("%d\n", t.step);
while (t1.pre != NULL) {
s.push(t1.op);
t1 = *t1.pre;
}
while (!s.empty()) {
int op = s.top();
switch (op) {
case 0: printf ("FILL(1)\n"); break;
case 1: printf ("FILL(2)\n"); break;
case 2: printf ("DROP(1)\n"); break;
case 3: printf ("DROP(2)\n"); break;
case 4: printf ("POUR(1,2)\n"); break;
case 5: printf ("POUR(2,1)\n"); break;
default: printf ("error\n");
}
s.pop();
}
return;
}
void BFS()
{
cnt = 0;
vis[0][0] = 1;
q.push(node(0, 0, NULL, -1, 0));
while (!q.empty()) {
Node[cnt] = q.front();
node t = Node[cnt];
if (t.x == c || t.y == c) {
outP (t);
return;
}
q.pop();
int a1, b1;
for (int i = 0; i < 6; i++) {
switch (i) {
case 0: a1 = a; b1 = t.y; break;
case 1: a1 = t.x; b1 = b; break;
case 2: a1 = 0; b1 = t.y; break;
case 3: a1 = t.x; b1 = 0; break;
case 4:{
int pour = b - t.y;
if (pour > t.x) {
a1 = 0;
b1 = t.x + t.y;
} else {
a1 = t.x - pour;
b1 = b;
}
break;
}
case 5:{
int pour = a - t.x;
if (pour > t.y) {
b1 = 0;
a1 = t.x + t.y;
} else {
b1 = t.y - pour;
a1 = a;
}
break;
}
default: printf("error\n");
}
if (!vis[a1][b1]) {
vis[a1][b1] = 1;
q.push(node(a1, b1, &Node[cnt], i, t.step + 1));
}
}
cnt++;
}
printf ("impossible\n");
return;
}
int main()
{
scanf ("%d%d%d", &a, &b, &c);
memset (vis, 0, sizeof(vis));
BFS ();
return 0;
}
本文介绍了一种使用广度优先搜索解决水罐问题的算法实现。通过定义节点结构存储水罐的状态及其操作历史,该算法能够找到从初始状态到达目标状态的一系列步骤。具体包括填充、倾倒和水罐间转移等操作。
&spm=1001.2101.3001.5002&articleId=79386466&d=1&t=3&u=1d1f00b26de34ac588bb8bcebb77ada6)
441

被折叠的 条评论
为什么被折叠?



