题目链接:https://www.dotcpp.com/oj/problem1426.html
题目描述
如下面第一个图的九宫格中,放着 1~8 的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。经过若干次移动,可以形成第二个图所示的局面。
我们把第一个图的局面记为:12345678.
把第二个图的局面记为:123.46758
显然是按从上到下,从左到右的顺序记录数字,空格记为句点。
本题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。如果无论多少步都无法到达,则输出-1。
输入
输入第一行包含九宫的初态,第二行包含九宫的终态。
输出
输出最少的步数,如果不存在方案,则输出-1。
样例输入
12345678. 123.46758
样例输出
3
解题思路:
总的来说题意就是看两个字符串经过最少多少步能成为相同的,我是用广搜做的,有上下左右四个方向,把把两个位置的数字和'.'调换,看和想要的字符串是否相同,用map记录字符串是否出现过,这样只要搜到就一定是最短的。结果很不幸的超时了。最后用了双向BFS,把尾部的字符串也加入队列,同时搜索,用maps标记字符串是否出现过,如果是从初态转化而来,标记为1,如果是从终态转化而来,标记为2,用temp来记录步数,当双方有交替的时候就证明搜索成功。
#include <bits/stdc++.h>
using namespace std;
const int N = 10;
char a[N], b[N];
int nex[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
map<string, int>maps;
map<string, int>temp;
int BFS()
{
if(strcmp(a, b)==0)
return 0;
queue<string>q;
q.push(a);
q.push(b);
while(!q.empty()) {
string head = q.front();
q.pop();
int x, y, t;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++) {
t = i*3+j;
if(head[t]=='.') {
x=i;
y=j;
break;
}
}
t=x*3+y;
for(int i=0; i<4; i++) {
int tx = x+nex[i][0];
int ty = y+nex[i][1];
if(tx>=0 && tx<3 && ty>=0 && ty<3) {
int r=tx*3+ty;
string tail = head;
tail[t] = tail[r];
tail[r] = '.';
if(!maps[tail]) {
maps[tail] = maps[head];
temp[tail] = temp[head]+1;
q.push(tail);
}
else if(maps[head]+maps[tail]==3){
return temp[head]+temp[tail]+1;
}
}
}
}
return -1;
}
int main()
{
scanf("%s%s", a, b);
maps[a]=1;
maps[b]=2;
printf("%d\n", BFS());
return 0;
}