标签:
1 #include<iostream> 2 #include<queue> 3 #include<algorithm> 4 #include<string> 5 #include<cstring> 6 #include<cstdio> 7 //正向广度搜索 8 //把“x"当初0 9 using namespace std; 10 11 const int maxn = 1000000; 12 13 int fac[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; //康拖展开判重 14 // 0!1!2!3! 4! 5! 6! 7! 8! 9! 15 int vis[maxn]; 16 17 int get_priority(int s[]){ //康拖展开求该序列的hash值 18 int sum = 0; 19 for (int i = 0; i<9; i++){ 20 int cnt = 0; 21 for (int j = i + 1; j<9; j++) 22 if (s[i]>s[j]) 23 cnt++; 24 sum += (cnt*fac[9 - i - 1]); 25 } 26 return sum + 1; 27 } 28 29 struct node{ 30 int s[9]; 31 int loc; //“0”的位置,把“x"当0 32 int status; //康拖展开的hash值 33 string path; //路径 34 }start; 35 36 string path; 37 int aim = 46234; //123456780对应的康拖展开的hash值 38 int dir[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };//u,d,l,r 39 char indexs[5] = "udlr";//正向搜索 40 41 int BFS(){ 42 queue<node> q; 43 while (!q.empty()) 44 q.pop(); 45 node cur, next; 46 q.push(start); 47 int x, y; 48 while (!q.empty()){ 49 cur = q.front(); 50 q.pop(); 51 if (cur.status == aim){ 52 path = cur.path; 53 return 1; 54 } 55 x = cur.loc / 3; 56 y = cur.loc % 3; 57 for (int i = 0; i<4; i++){ 58 int tx = x + dir[i][0]; 59 int ty = y + dir[i][1]; 60 if (tx<0 || tx >= 3 || ty<0 || ty >= 3) 61 continue; 62 next = cur; 63 next.loc = tx * 3 + ty; 64 next.s[cur.loc] = next.s[next.loc]; 65 next.s[next.loc] = 0; 66 next.status = get_priority(next.s); 67 if (!vis[next.status]){ 68 vis[next.status] = 1; 69 next.path = next.path + indexs[i]; 70 if (next.status == aim){ 71 path = next.path; 72 return 1; 73 } 74 q.push(next); 75 } 76 } 77 } 78 return 0; 79 } 80 81 int main(){ 82 83 //freopen("input.txt","r",stdin); 84 85 char ch; 86 while (cin >> ch){ 87 if (ch == ‘x‘){ 88 start.s[0] = 0; 89 start.loc = 0; 90 } 91 else 92 start.s[0] = ch - ‘0‘; 93 for (int i = 1; i<9; i++){ 94 cin >> ch; 95 if (ch == ‘x‘){ 96 start.s[i] = 0; 97 start.loc = i; 98 } 99 else 100 start.s[i] = ch - ‘0‘; 101 } 102 start.status = get_priority(start.s); 103 memset(vis, 0, sizeof(vis)); 104 if (BFS()) 105 cout << path << endl; 106 else 107 printf("unsolvable\n"); 108 } 109 return 0; 110 }
标签:
原文地址:http://www.cnblogs.com/usedrosee/p/4341490.html