在一个 3×33×3 的网格中,1∼81∼8 这 88 个数字和一个 x
恰好不重不漏地分布在这 3×33×3 的网格中。
例如:
1 2 3
x 4 6
7 5 8
在游戏过程中,可以把 x
与其上、下、左、右四个方向之一的数字交换(如果存在)。
我们的目的是通过交换,使得网格变为如下排列(称为正确排列):
1 2 3
4 5 6
7 8 x
例如,示例中图形就可以通过让 x
先后与右、下、右三个方向的数字交换成功得到正确排列。
交换过程如下:
1 2 3 1 2 3 1 2 3 1 2 3
x 4 6 4 x 6 4 5 6 4 5 6
7 5 8 7 5 8 7 x 8 7 8 x
现在,给你一个初始网格,请你求出得到正确排列至少需要进行多少次交换。
输入格式
输入占一行,将 3×33×3 的初始网格描绘出来。
例如,如果初始网格如下所示:
1 2 3
x 4 6
7 5 8
则输入为:1 2 3 x 4 6 7 5 8
输出格式
输出占一行,包含一个整数,表示最少交换次数。
如果不存在解决方案,则输出 −1−1。
输入样例:
2 3 4 1 5 x 7 6 8
输出样例
19
解题思路:通过广搜进行遍历,取得最终答案
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<queue>
using namespace std;
int nx[] = {-1,0,0,1};
int ny[] = {0,-1,1,0};
int BFS(string str)
{
string end = "12345678x"; //末状态字符串
//定义队列与dist数组
queue<string> que;
unordered_map<string,int> dist;
//初始化
que.push(str);
dist[str] = 0;
while(que.size())
{
string temp = que.front();//中间变量
que.pop();
int distance = dist[temp];//状态变化得到最小值
if(temp == end)return distance;
int k = temp.find('x');//找到x所在位置
int x = k / 3,y = k % 3;
for(int i = 0; i < 4; i++)
{
int tx = x + nx[i];
int ty = y + ny[i];
if(tx < 0 || ty < 0 || tx > 2 || ty > 2)continue;
swap(temp[k],temp[3 * tx + ty]); //状态改变
if(!dist[temp])
{
//没变成过这种状态,则进行记录,并且步数加一
dist[temp] = distance + 1;
//加入队列中,继续遍历
que.push(temp);
}
swap(temp[k],temp[3 * tx + ty]); //状态复原,为下一次转换做准备
}
}
return -1;
}
int main()
{
string start,c;
for(int i = 0; i < 9; i++)
{
cin>>c;
start += c;
}
cout<<BFS(start)<<endl;//开始广搜,以初始字符串为参数
return 0;
}