题:假设杯子容量为6,3,1。杯子没有刻度。给定初始状态和目标状态,最少需要多少步才能从初始状态转为目标状态。
#include <iostream>
using namespace std;
int vol[3] = { 6, 3, 1 };
typedef int state[3]; //定义状态类型
const int MAXSTATE = 1000000;
state st[MAXSTATE], goal; //状态数组
int dist[MAXSTATE]; //距离数组
int front = 0, rear = 1;
int pull[][2] = { { 0, 1 }, { 0, 2 },
{ 1, 0 }, { 1, 2 },
{ 2, 0 }, { 2, 1 } };
int isExist(state& s)
{
for (int i = 0; i < rear; i++) {
if (s[0] == st[i][0] && s[1] == st[i][1]) {
return 1;
}
}
return 0;
}
int pullWater(state &s, int from, int to)
{
if (s[from] != 0 && s[to] != vol[to]) {
state &newState = st[rear];
memcpy(&newState, &s, sizeof(s));
if (s[from] >= (vol[to] - s[to])) {
newState[from] = s[from] - (vol[to] - s[to]);
newState[to] = vol[to];
}
else {
newState[to] = newState[to] + newState[from];
newState[from] = 0;
}
if (!isExist(newState)) {
return 1;
}
}
return 0;
}
int bfs()
{
int ok = 0;
while (front < rear) {
state &s = st[front];
if (memcmp(goal, s, sizeof(s)) == 0)
{
return front;
}
for (int i = 0; i < 6; i++) {
ok = pullWater(s, pull[i][0], pull[i][1]);
if (ok == 1) {
dist[rear] = dist[front] + 1;
rear++;
}
}
front++;
}
return -1;
}
int main()
{
for (int i = 0; i < 3; i++) {
cin >> st[0][i];
}
for (int i = 0; i < 3; i++) {
cin >> goal[i];
}
int ans = bfs();
if (ans >= 0) {
cout << dist[ans];
}
else {
cout << -1;
}
int a;
cin >> a;
return 0;
}