主页面:http://www.cnblogs.com/DOLFAMINGO/p/7538588.html
代码一:像BFS那样,把棋盘数组放在结构体中。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <vector> 7 #include <queue> 8 #include <stack> 9 #include <map> 10 #include <string> 11 #include <set> 12 #define ms(a,b) memset((a),(b),sizeof((a))) 13 using namespace std; 14 typedef long long LL; 15 const int INF = 2e9; 16 const LL LNF = 9e18; 17 const int MOD = 1e9+7; 18 const int MAXN = 1e6+10; 19 #define AIM 1 //123456789的哈希值为1 20 21 struct node 22 { 23 int s[9]; 24 int loc; 25 }; 26 27 int fac[9] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320}; 28 int dir[4][2] = { -1,0, 1,0, 0,-1, 0,1 }; 29 char op[4] = {'u', 'd', 'l', 'r' }; 30 31 int cantor(int s[]) //获得哈希函数值 32 { 33 int sum = 0; 34 for(int i = 0; i<9; i++) 35 { 36 int num = 0; 37 for(int j = i+1; j<9; j++) 38 if(s[j]<s[i]) num++; 39 sum += num*fac[8-i]; 40 } 41 return sum+1; 42 } 43 44 int dis_h(int s[]) //获得曼哈顿距离 45 { 46 int dis = 0; 47 for(int i = 0; i<9; i++) 48 if(s[i]!=9) 49 { 50 int x = i/3, y = i%3; 51 int xx = (s[i]-1)/3, yy = (s[i]-1)%3; 52 dis += abs(x-xx) + abs(y-yy); 53 } 54 return dis; 55 } 56 57 char path[100]; 58 bool IDAstar(node now, int depth, int pre, int limit) 59 { 60 if(dis_h(now.s)==0) //搜到123456789 61 { 62 path[depth] = '