标签:
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 30127 | Accepted: 13108 | Special Judge |
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->
1 2 3
x 4 6
7 5 8
1 2 3 x 4 6 7 5 8
2 3 4 1 5 x 7 6 8
ullddrurdllurdruldr
POJ上的数据比较水,杭电服务器维护,明天到杭电上提交试试
1 //2016.8.25 2 #include<iostream> 3 #include<cstdio> 4 #include<algorithm> 5 #include<map> 6 7 using namespace std; 8 9 int a[10][10], b[10], d[1000], sx, sy, deep; 10 bool ok; 11 map<int, bool> vis; 12 char dir[4] = {‘u‘, ‘d‘, ‘l‘, ‘r‘}; 13 int dx[4] = {-1, 1, 0, 0}; 14 int dy[4] = {0, 0, -1, 1}; 15 16 bool solve()//求逆序对判断是否有解 17 { 18 int cnt = 0; 19 for(int i = 1; i <= 9; i++) 20 for(int j = 0; j < i; j++) 21 if(b[i] && b[j]>b[i]) 22 cnt++; 23 return !(cnt%2); 24 } 25 26 int Astar() 27 { 28 int h = 0; 29 for(int i = 1; i <= 3; i++) 30 for(int j = 1; j <= 3; j++) 31 if(a[i][j]!=0) 32 { 33 int nx = (a[i][j]-1)/3; 34 int ny = (a[i][j]-1)%3; 35 h += (abs(i-nx-1)+abs(j-ny-1)); 36 } 37 return h; 38 } 39 40 int toInt()//把矩阵转换为int型数字 41 { 42 int res = 0; 43 for(int i = 1; i <= 3; i++) 44 for(int j = 1; j <= 3; j++) 45 res = res*10+a[i][j]; 46 return res; 47 } 48 49 void IDAstar(int x, int y, int step) 50 { 51 if(ok)return ; 52 int h = Astar(); 53 if(!h && toInt()==123456780)//找到答案 54 { 55 for(int i = 0; i < step; i++) 56 cout<<dir[d[i]]; 57 cout<<endl; 58 ok = 1; 59 return ; 60 } 61 if(step+h>deep)return ; 62 int now = toInt(); 63 if(vis[now])return ; 64 vis[now] = true; 65 for(int i = 0; i < 4; i++) 66 { 67 int nx = x+dx[i]; 68 int ny = y+dy[i]; 69 if(nx>=1&&nx<=3&&ny>=1&&ny<=3) 70 { 71 d[step] = i; 72 swap(a[x][y], a[nx][ny]); 73 IDAstar(nx, ny, step+1); 74 swap(a[x][y], a[nx][ny]); 75 d[step] = 0; 76 } 77 } 78 return; 79 } 80 81 int main() 82 { 83 char ch; 84 while(cin >> ch) 85 { 86 ok = false; 87 deep = 0; 88 int cnt = 0; 89 for(int i = 1; i <= 3; i++) 90 { 91 for(int j = 1; j <= 3; j++) 92 { 93 if(i==1&&j==1); 94 else cin >> ch; 95 if(ch == ‘x‘) 96 { 97 a[i][j] = 0; 98 sx = i; 99 sy = j; 100 }else 101 a[i][j] = ch - ‘0‘; 102 b[cnt++] = a[i][j]; 103 } 104 } 105 if(!solve()) 106 { 107 cout<<"unsolvable"<<endl; 108 continue; 109 } 110 while(!ok) 111 { 112 vis.clear(); 113 IDAstar(sx, sy, 0); 114 deep++; 115 } 116 } 117 118 return 0; 119 }
标签:
原文地址:http://www.cnblogs.com/Penn000/p/5808582.html