【搜索】测试题E-魔板

题意

一个二维的“魔方”,给出三种变化方式,求从基础状态(12345678)到目标状态的操作数以及操作方法

思路

可以把每次变换形成的状态当成一个点,找出从一开始基础状态到目标状态所需要的最小的步数

首先是三种状态变化的函数,(ps刚开始没写对就是因为变换的函数居然写错了)。

要注意的地方是,读数的方法是是顺时针数的,以及可以使用substr()函数。

其次的话,用map来记录访问的状态,对字符串做ABC三种变换,直至与目标字符串相等即可

代码

#include<iostream>
#include<cmath>
#include<stack>
#include<map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>

#define Endl "\n"
typedef long long ll;
const int maxn=8;
const int mod=1e9+7;
using namespace std;
int a[8];
int num[8];
char ans[10005];

string A(string s)
{
	string sa="";
	char A[3][5]={0};
	for(int i=0;i<4;i++)
		A[0][i]=s[i];
	for(int i=0;i<4;i++)
		A[1][i]=s[7-i];
	for(int i=0;i<4;i++)
		swap(A[0][i],A[1][i]);
		
	for(int i=0;i<4;i++) 
		sa+=A[0][i];
	for(int i=3;i>=0;i--) 
		sa+=A[1][i];
	return sa; 
}

string B(string s)
{
	return s[3]+s.substr(0,3)+s.substr(5,3)+s[4];
}

string C(string s)
{
	return s[0]+s.substr(6,1)+s[1]+s.substr(3,2)+s[2]+s.substr(5,1)+s[7];
}

struct node{
	string s;
	int step;
	string method;
};

map <string,bool> Map;
void bfs(string s)
{
//	cout<<"here1"<<Endl;
	queue <node> q;
	q.push({"12345678",0,""});
	Map["12345678"]=true;
	while(!q.empty())
	{
//		cout<<"here2"<<Endl;
		node t =q.front();
//		cout<<t.s<<" "<<t.step<<" "<<t.method<<Endl;
		q.pop();
		if(t.s==s)
		{
//			cout<<"----ans---"<<Endl;
			cout<<t.step<<Endl;
			if(t.step>0)	cout<<t.method<<Endl;
			break;
		}
		string sa=A(t.s);
		if(!Map[sa])
		{
			q.push({sa,t.step+1,t.method+"A"});
			Map[sa]=true;
//			cout<<"AA"<<Endl;
		}
		
		string sb=B(t.s);
		if(!Map[sb])
		{
			q.push({sb,t.step+1,t.method+"B"});
			Map[sb]=true;
//			cout<<"BB"<<Endl;
		}
		
		string sc=C(t.s);
		if(!Map[sc])
		{
			q.push({sc,t.step+1,t.method+"C"});
			Map[sc]=true;
//			cout<<"CC"<<Endl;
		}
	}
}
int main()
{
	string s="";
	for(int i=0;i<8;i++)
	{
		char c;
		cin>>c;
		s+=c;
	}
	bfs(s);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值