隐式状态图的BFS,参考POJ 1606 3414 1606的代码如下, #include <iostream> #include <queue> #include <stack> using namespace std; class S { public: int x; int y; int op; S* p; S(int x = 0, int y = 0, int op = 0, S* p = 0):x(x),y(y),op(op),p(p){} bool operator==(int c) { return (y == c); } }; queue<S*> q; int A; int B; int C; bool hash[101][101]; S* getState(S *s, int op) { int x = s->x; int y = s->y; S* ns = 0; switch(op) { case 0: // fill 1 if( x < A ) { x = A; ns = new S(x, y, 0, s); } break; case 1: // fill 2 if( y < B ) { y = B; ns = new S(x, y, 1, s); } break; case 2: // drop 1 if (x > 0) { x = 0; ns = new S(x, y, 2, s); } break; case 3: // drop 2 if (y > 0) { y = 0; ns = new S(x, y, 3, s); } break; case 4: // pour(1,2) if(x > B - y) { x = x - (B-y); y = B; ns = new S(x, y, 4, s); } else if(x>0) { y = y + x; x = 0; ns = new S(x, y, 4, s); } break; case 5: // pour(2,1) if( y > A - x) { y = y - (A-x); x = A; ns= new S(x, y, 5, s); } else if(y > 0) { x = x + y; y = 0; ns = new S(x, y, 5, s); } break; } return ns; } void print(int op) { switch(op) { case 0: cout << "fill A" << endl; break; case 1: cout << "fill B" << endl; break; case 2: cout << "empty A" << endl; break; case 3: cout << "empty B" << endl; break; case 4: cout << "pour A B" << endl; break; case 5: cout << "pour B A" << endl; break; } } void BFS() { int x, y; while(!q.empty()) { S* ps = q.front(); q.pop(); if(*ps == C) { stack<int> st; while(ps->p) { st.push(ps->op); ps = ps->p; } while(!st.empty()) { print(st.top()); st.pop(); } cout << "success" << endl; return; } for(int i = 0; i < 6; i++) { S *ns = getState(ps, i); // cout << i << (s ? s->x : -1) << (s ? s->y: -1) << endl; if(ns && !hash[ns->x][ns->y]) { hash[ns->x][ns->y] = true; //cout << "push(" << ns->x << "," << ns->y <<")" << ns->op << ", " << ns-> p << endl; q.push(ns); } } } } int main() { while(cin >> A >> B >> C) { for(int i = 0; i < 101; i++) { for(int j = 0; j < 101; j++) { hash[i][j] = false; } } while(!q.empty()) { q.pop(); } hash[0][0] = true; S s(0, 0); q.push(&s); BFS(); } }