poj1077:Eight

传送门
注意本题是special judge,有多组最优解只需输出一组,不必要字典序排序

#include<iostream>
#include<queue>
#include<unordered_map>
using namespace std;
const string End="12345678x";
const int dx[]={
    
    -1,0,1,0},dy[]={
    
    0,-1,0,1};
const char str[]="uldr";
string bfs(string start)
{
    
    	
	unordered_map <string,string>path;
	queue<string>q;
	q.push(start);
	while(q.size())
	{
    
    
		auto t=q.front();
		q.pop();
		string res=path[t];
		if(t==End)return res;
		int k=t.find('x');
		int x=k/3,y=k%3;
		for(int i=0;i<4;i++)
		{
    
    
			int tx=x+dx[i],ty=y+dy[i];
			if(tx>=0&&ty>=0&&tx<3&&ty<3)
			{
    
    
				swap(t[k],t[tx*3+ty]);
				if(!path.count(t))
				{
    
    
					path[t]=res+str[i];
					q.push(t);
				}
				swap(t[k],t[tx*3+ty]);
			}
		}
	}
	return "unsolvable";
} 
using namespace std;
int main()
{
    
    
	string start;
	for(int i=0;i<9;i++)
	{
    
    
		char c;
		cin>>c;
		start+=c;
	}
	cout<<bfs(start)<<endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_49640089/article/details/114994821