在一个 3×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。
(题目来源转载自acwing)
解题思路:利用字符串存储网格,哈希表存储步数,总体通过bfs暴力搜索即可。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<unordered_map> //用哈希表存储步数
#include<string>
using namespace std;
const int N = 3 + 10;
string s; //用字符串存储3x3表格
queue<string> q;
unordered_map<string,int> h;
int dx[4] = {1,0,-1,0},dy[4] = {0,1,0,-1};
int bfs(string s){
q.push(s);
h[s] = 0; //初始化
while(!q.empty()){
string t = q.front();
q.pop();
if(t == "12345678x") return h[t];
int dist = h[t]; //记录没走之前的步数
int pos = t.find('x');
int x = pos / 3,y = pos % 3; //这里非常重要,把字符串还原成坐标的形式
for(int i = 0;i < 4;i++){
int tx = x + dx[i],ty = y + dy[i];
if(tx >= 0 && tx < 3 && ty >= 0 && ty < 3){
swap(t[3 * tx + ty],t[pos]); //这里再还原回来
if(h.find(t) == h.end()){
h[t] = dist + 1;
q.push(t);
}
swap(t[3 * tx + ty],t[pos]);
}
}
}
return -1;
}
int main(){
for(int i = 0;i < 9;i++){
char c;
cin>>c;
s += c; //用字符串存储
}
cout<<bfs(s)<<endl;
return 0;
}