HDU-1043 Eight 八数码问题

来源:互联网 发布:艾滋病感染概率 知乎 编辑:程序博客网 时间:2024/05/19 16:34

http://acm.hdu.edu.cn/showproblem.php?pid=1043


#include<stdio.h>#include<iostream>#include<string>#include<string.h>#include<vector>#include<queue>#include<map>#include<algorithm>using namespace std;const int maxn = 105;const int inf = 1<<30;int xs[] = {0,1,0,-1};int ys[] = {1,0,-1,0};int goal[10] = {1,2,3,4,5,6,7,8,9};char dir[] = { 'l','u','r','d' };int mod[] = {100000000,10000000,1000000,100000,10000,1000,100,10,1};int s[10];int counts;int pos = 0;string path[192000];map<int,int>mark;struct node{int p;int k;int id;};int fun( node x,int k ){int ans = x.p,w,temp;w = (ans/mod[k])%10;        //ans += (9-w)*mod[k];ans -= (9-w)*mod[x.k];return ans;}void BFS(){node cur,cnt;queue<node>que;cur.p = 123456789; cur.k = 8;cur.id = 0;que.push(cur);while ( !que.empty() ){cur = que.front(); que.pop();int x = cur.k/3,y = cur.k%3;for( int i = 0; i < 4; i ++ ){int xx = x + xs[i];int yy = y + ys[i];cnt.k = xx*3 + yy;if( xx >= 0 && xx < 3 && yy >= 0 && yy < 3 ){cnt.p = fun( cur,cnt.k );if( mark[cnt.p] )continue;path[++pos] = dir[i] + path[cur.id];cnt.id = pos;mark[cnt.p] = pos;counts ++;que.push( cnt );}}}}int main(){//freopen("data.txt","r",stdin);char str[50];int num;BFS();while ( gets(str) ){num = 0;for ( int i = 0; str[i]; i ++ ){if( str[i] == 'x' )num= num *10 + 9;else if( str[i] != ' ' )num = num*10 + str[i] - '0';}int ans = mark[num];if( ans )cout<<path[ans]<<endl;elseputs("unsolvable");}return 0;}


原创粉丝点击