八数码问题 暴力搜索例题

题目:
在这里插入图片描述
AC代码:

#include <bits/stdc++.h>
using namespace std;
string s;
unordered_map<string,string> m;
bool check(string x)
{
	return x==(string)"12345678x";
}
int main()
{
	cin>>s;
	queue<string> q;
	q.push(s);
	m[s]="-1";
	while (!q.empty())
	{
		string now=q.front();
		//cout<<"now="<<now<<endl;
		string onow=now;
		q.pop();
		int pos;
		for (int i=0;i<9;i++) if (now[i]=='x') pos=i;
		if (pos>2)
		{
			swap(now[pos],now[pos-3]);
			if (m.find(now)==m.end()) 
			{
				m[now]=onow;
				if (check(now)) break;
				q.push(now);
			}
			swap(now[pos],now[pos-3]);
		}
		if (pos<6) 
		{
			swap(now[pos],now[pos+3]);
			if (m.find(now)==m.end()) 
			{
				m[now]=onow;
				if (check(now)) break;
				q.push(now);
			}
			swap(now[pos],now[pos+3]);
		}
		
		if (pos%3!=0)
		{
			swap(now[pos],now[pos-1]);
			if (m.find(now)==m.end()) 
			{
				m[now]=onow;
				if (check(now)) break;
				q.push(now);
			}
			swap(now[pos],now[pos-1]);
		}
		if (pos%3!=2)
		{
			swap(now[pos],now[pos+1]);
			if (m.find(now)==m.end()) 
			{
				m[now]=onow;
				if (check(now)) break;
				q.push(now);
			}
			swap(now[pos],now[pos+1]);
		}
	}
	vector<string> out;
	string tar="12345678x";
	if(m.find(tar)!=m.end())
	{
		for (;tar!="-1";tar=m[tar]) 
		{
			out.push_back(tar);
		}
		reverse(out.begin(),out.end());
		//cout<<out.size()<<endl;
		//for (auto x:out) cout<<x<<endl;
		for (int i=0;i<(int)out.size()-1;i++)
		{
			int temp1,temp2;
			for(int j=0;j<(int)out[i].size();j++)
			{
				if(out[i][j]=='x') temp1=j;
			}
			for(int j=0;j<(int)out[i+1].size();j++)
			{
				if(out[i+1][j]=='x') temp2=j;
			}
			if(temp2-temp1==3) cout<<"d";
			if(temp2-temp1==-3) cout<<"u";
			if(temp2-temp1==1) cout<<"r";
			if(temp2-temp1==-1) cout<<"l";
		}
		cout<<endl;
	}
	else cout<<"unsolvable"<<endl;
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值