思路:BFS
乍一看,大家根本想不出来这是一个bfs题。很巧妙,这就是一个bfs的遍历题。
我们看到样例的解释,无非就是对于0的位置的交换。那我们可以这样想:
如果我不是在一个字符串里面操作,而是在一个二维数组里面操作呢?那就另当别论了,我们可以将这个一维的字符串看作是二维的空间。
将这个字符串想象它已经转化为了二维的空间,我们该怎么做?当然是从0开始进行遍历操作了。
我们上下左右进行遍历,然后记录距离就可以。但是,题目终究是一维的,我们该怎么记录呢?总不能用二维数组进行存储吧?哈哈,这就是哈希表的巧用了。我们用映射的方式来完成这个过程。
代码里有注释,大家放心参考。
上代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<deque>
#include <iomanip>
#include<sstream>
#include<numeric>
#include<map>
#include<limits.h>
#include<unordered_map>
#include<set>
#define int long long
#define MAX 501
#define _for(i,a,b) for(int i=a;i<(b);i++)
#define ALL(x) x.begin(),x.end()
using namespace std;
typedef pair<int, int> PII;
int n, m;
int counts;
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
char maps[MAX][MAX];
unordered_map<string, int>dist;//每一种字符串代表的移动次数,二维存储变成映射
queue<string>q;
string s;
string mudi = "123804765";
int bfs() {
q.push(s);
dist[s] = 0;
while (!q.empty()) {
auto t = q.front();
q.pop();
int dis = dist[t];
if (t == mudi)
return dist[t];
int biao = t.find('0');//找到0在字符串中的位置
int stx = biao / 3;//一维转二维,这里是二维的行数
int sty = biao % 3;//这里是二维的列数
_for(i, 0, 4) {
int a = dx[i] + stx;
int b = dy[i] + sty;
if (a < 0 || a >= 3 || b < 0 || b >= 3)
continue;
int tmp = a * 3 + b;//这里就是对于二维转一维,转的是坐标,和上面的原理相呼应
swap(t[biao], t[tmp]);//原先0的位置和我们现在遍历到的位置互相交换,这个时候字符串已经不是原来的字符串了。
if (!dist.count(t)) {//如果我们通过遍历而构成的字符串没有被遍历到的,也就是找是不是已经被遍历过了。
dist[t] = dis + 1;//原来的字符串的次数是dis,这次又变化了一下,就得+1,这个字符串是交换后的字符串。
q.push(t);//加入新的字符串
}
swap(t[biao], t[tmp]);//恢复现场,因为我们还有别的状态没有遍历完,需要在原先的状态上进行。
}
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> s;
cout << bfs() << endl;
return 0;
}