蓝桥杯历届试题-九宫重排

解题思路:题目给了我们2个字符串,因为是求最小值所以我们首先想到的应该是用BFS来做这道题(我这个憨憨一开始竟然是用DFS做的,我是真服了自己了),首先我们先要把题目给我们的起始字符串转化成二维数组,连带着把空格的坐标,当前的要走的步数弄成一个结构体,放到队列里面去宽搜,宽搜的时候注意把当前的状态再次转换成字符串标记一下状态,如果走到了终点就更新一下答案,如果当前状态没有走过就标记一下,放到队列里面,还要注意状态的转移,应该是把当前位置上的数变成搜到的位置上的数,搜到的位置上填'.'(空格),最后输出答案就好了。

上代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
string str1,str2;
char st[10][10],en[10][10];
int sx,sy,ex,ey;
int dx[]={-1,1,0,0},dy[]={0,0,-1,1};
struct node {
	char sz[10][10];
	int step,x,y;
};
map<string,int>mp;
int main()
{
	cin>>str1>>str2;
	node s;
	for(int i=0;i<3;i++)
    s.sz[1][i+1]=str1[i];
    for(int i=3;i<6;i++)
    s.sz[2][i-2]=str1[i];
    for(int i=6;i<9;i++)
    s.sz[3][i-5]=str1[i];
    for(int i=1;i<=3;i++)
    	for(int j=1;j<=3;j++)
    		if(s.sz[i][j]=='.')
    		s.x=i,s.y=j;
    queue<node>que;
    int ans=0x3f3f3f3f;
    que.push(s);	
    while(que.size())
    {
    	auto t=que.front();
    	que.pop();
    	for(int i=0;i<4;i++)
    	{
    		node temp=t;
    		temp.x=t.x+dx[i];
    		temp.y=t.y+dy[i];
    		if(temp.x<1||temp.x>3||temp.y<1||temp.y>3)
    		continue;
    		temp.step=t.step+1;
    		temp.sz[t.x][t.y]=temp.sz[temp.x][temp.y];
    		temp.sz[temp.x][temp.y]='.';
    		string str="";
    		for(int j=1;j<=3;j++)
    			for(int k=1;k<=3;k++)
    			str+=temp.sz[j][k];
    		if(str==str2)
			{
				ans=min(ans,temp.step);
				continue;
			 } 
    		if(!mp[str])
    		{
    			mp[str]=1;
    			que.push(temp);
			}
		}
	}
	if(ans==0x3f3f3f3f)
	cout<<"-1"<<endl;
	else
	cout<<ans<<endl;
	return 0;
 } 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值