HDU-1043 Eight 八数码问题

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;
		else
			puts("unsolvable");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值