1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 x
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8 9 x 10 12 9 10 x 12 9 10 11 12 9 10 11 12 13 14 11 15 13 14 11 15 13 14 x 15 13 14 15 x r-> d-> r->
2 3 4 1 5 x 7 6 8
ullddrurdllurdruldr
8数码问题网上解说很多,我是用康托展开做的
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; int s[20],pos[20],end[20]; int hash[20],vis[1000000]; string ans[1000000]; struct node { string step; int num[10],val; int pp; }; int solve(int s[]) { int sum=0; for(int i=0; i<9; i++) { int num=0; for(int j=i+1; j<9; j++) if(s[j]<s[i])num++; sum+=(num*hash[9-i-1]); } return sum+1; } int to[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; char path[10] = "durl"; void bfs() { memset(vis,0,sizeof(vis)); int i,j; node a,next; queue<node> Q; for(i = 0; i<8; i++) a.num[i] = i+1; a.num[8] = 0; a.pp = 8; a.step = ""; a.val = 46234; ans[a.val] = ""; Q.push(a); while(!Q.empty()) { a = Q.front(); Q.pop(); int x = a.pp/3; int y = a.pp%3; for(i = 0; i<4; i++) { int tx = x+to[i][0]; int ty = y+to[i][1]; if(tx<0 || ty<0 || tx>2 || ty>2) continue; next = a; next.pp = 3*tx+ty; next.num[a.pp] = next.num[next.pp]; next.num[next.pp] = 0; next.val = solve(next.num); if(!vis[next.val]) { vis[next.val]=true; next.step=path[i]+next.step; Q.push(next); ans[next.val]=next.step; } } } } int main() { int i; char ch; node a; int c[10]; hash[0] = 1; for(i = 1; i<=10; i++) hash[i] = hash[i-1]*i; bfs(); while(cin >> ch) { if(ch == ‘x‘) c[0] = 0; else c[0]=ch-‘0‘; for(int i=1; i<9; i++) { cin>>ch; if(ch==‘x‘) c[i]=0; else c[i]=ch-‘0‘; } int k; k = solve(c); if(vis[k]) cout << ans[k] << endl; else cout << "unsolvable" << endl; } return 0; }
HDU1043:Eigth(康托展开),布布扣,bubuko.com
原文:http://blog.csdn.net/libin56842/article/details/22999563