[蓝桥杯][历届试题]九宫重排

题目链接
如下面第一个图的九宫格中,放着 1~8 的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。经过若干次移动,可以形成第二个图所示的局面。
在这里插入图片描述

我们把第一个图的局面记为:12345678.
把第二个图的局面记为:123.46758
显然是按从上到下,从左到右的顺序记录数字,空格记为句点。
本题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。如果无论多少步都无法到达,则输出-1。

题解

这是我写过的第一道双向BFS的问题(大雾)
双向BFS的一个好处就是从七点和终点开始分别BFS搜索,直到两个状态相同为止,这样讲大大提高搜索的效率, 不失为一种好方法。
再具体的实现方式上,使用一个string来存图,map这中映射很好用。数据结构使用队列,对于每一种状态,压到队列里。需要处理的一个细节就是map容器中存的“状态”是唯一的。
ans = cntM[now] + cntM[next] + 1
具体看代码,还是一道比较好的题,值得好好研究:

//双向 BFS 
#include <iostream>
#include <cstdio> 
#include <string>
#include <cstring>
#include <queue>
#include <map>
using namespace std;
string a, b;
int dx[4] = {0, 0, 1,-1};
int dy[4] = {1,-1, 0, 0};

string nextMatrix(string s,int dir)
{
	int pos = s.find('.');
	int xx = pos/3 + dx[dir];
	int yy = pos%3 + dy[dir];
	if (xx < 0 || yy < 0 || xx > 2 || yy > 2) return "NULL";
	swap(s[pos], s[xx*3 + yy]);
	return s;
}

map<string, int> cntM, dirM;
queue <string> q;
int BFS(string begin, string end)
{
	q.push(begin); q.push(end);
	cntM[begin] = 0; cntM[end] = 0;
	dirM[begin] = 1; dirM[end] = 2; //正向为 1,反向为 2 
	while (!q.empty())
	{
		string now = q.front();
		q.pop();
		for (int i = 0; i < 4; i ++)
		{
			string next = nextMatrix(now,i);
			if (next != "NULL" && dirM[next] != dirM[now])//
			{
				if (dirM[now] + dirM[next] == 3)
					return cntM[now] + cntM[next] + 1;
				q.push(next);
				cntM[next] = cntM[now] + 1;
				dirM[next] = dirM[now];
			}
		}
	}
}

int main()
{
	cin >> a >> b;
	cout << BFS(a, b);
	return 0;
}
/*
12345678.
123.46758
*/
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值