HDU 1043的加强版
8数码问题
给出8数码问题的两种状态,求从A状态到B状态的最优解,数据保证有解,若有多解,输出最短且字典序最小的。
基本思路和1043的差不多,只不过这次要预处理出来9种情况的BFS
即:
BFS(0,"012345678");
BFS(1,"102345678");
BFS(2,"120345678");
BFS(3,"123045678");
BFS(4,"123405678");
BFS(5,"123450678");
BFS(6,"123456078");
BFS(7,"123456708");
BFS(8,"123456780");
然后对于每次读入的A状态根据相应的0位置,对照BFS的表进行映射,转化为1043题型的搜索。
#include "stdio.h" #include "string.h" #include "queue" #include "string" using namespace std; const int dir[4][2]={{1,0},{0,-1},{0,1},{-1,0}}; const char indexs[]="dlru"; const int fac[]={1,1,2,6,24,120,720,5040,40320,362880}; char path[10][500010]; int time[10][500010],pri[10][500010],used[500010]; struct node { int status,loc,t; int s[9]; }; int Cantor(int b[]) { int i,j,sum,cnt; sum=0; for (i=0;i<=8;i++) { cnt=0; for (j=i+1;j<=8;j++) if (b[i]>b[j]) cnt++; sum+=cnt*fac[9-i-1]; } return sum+1; } void BFS(int w,char s[]) { queue<node>q; node cur,next; int i,x,y,xx,yy; for (i=0;i<=8;i++) cur.s[i]=s[i]-'0'; cur.loc=w; cur.t=0; cur.status=Cantor(cur.s); memset(used,0,sizeof(used)); used[cur.status]=1; q.push(cur); pri[w][cur.status]=-1; while (!q.empty()) { cur=q.front(); q.pop(); x=cur.loc/3; y=cur.loc%3; for (i=0;i<4;i++) { xx=x+dir[i][0]; yy=y+dir[i][1]; if (xx<0 || xx>2 || yy<0 || yy>2) continue; next=cur; next.loc=xx*3+yy; next.s[cur.loc]=next.s[next.loc]; next.s[next.loc]=0; next.status=Cantor(next.s); if (used[next.status]==0) { used[next.status]=1; next.t++; path[w][next.status]=indexs[i]; pri[w][next.status]=cur.status; time[w][next.status]=next.t; q.push(next); } } } } void output(int w,int key) { if (pri[w][key]==-1) return ; output(w,pri[w][key]); printf("%c",path[w][key]); } int main() { int T,key,j,i,Case,status; int a[10],b[10]; char s1[10],s2[10]; BFS(0,"012345678"); BFS(1,"102345678"); BFS(2,"120345678"); BFS(3,"123045678"); BFS(4,"123405678"); BFS(5,"123450678"); BFS(6,"123456078"); BFS(7,"123456708"); BFS(8,"123456780"); scanf("%d",&T); Case=0; while (T--) { Case++; scanf("%s%s",s1,s2); if (strcmp(s1,s2)==0) { printf("Case %d: 0\n\n",Case); continue; } for (i=0,j=0;i<=8;i++) if (s1[i]=='X') { key=i; a[0]=0;} else a[s1[i]-'0']=++j; for (i=0;i<=8;i++) if (s2[i]=='X') b[i]=a[0]; else b[i]=a[s2[i]-'0']; status=Cantor(b); printf("Case %d: %d\n",Case,time[key][status]); output(key,status); printf("\n"); } return 0; }
原文:http://blog.csdn.net/u011932355/article/details/44241715