题目链接
如下面第一个图的九宫格中,放着 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
*/