题目链接:
http://lx.lanqiao.cn/problem.page?gpid=T42
思路:
既然是求最少次数,那就用bfs搜索;
每次寻找下一种可能的状态,用map容器记录即可;
代码:
#include<bits/stdc++.h>
using namespace std;
bool tag[10][10];
string s, t, now;
map<string, int> cnt;
queue<string> que;
inline void bfs(int & p, int & q) {
int pre = cnt[now];
swap(now[p], now[q]);
if(now == t) {
cout << pre << '\n';
exit(0);
}
if(!cnt[now]) {
que.push(now);
cnt[now] = pre + 1;
}
swap(now[p], now[q]);
}
#define ok(x, y) tag[i * 3 + j][(x) * 3 + y] = tag[(x) * 3 + y][i * 3 + j] = true;
int main() {
#ifdef MyTest
freopen("Sakura.txt", "r", stdin);
#endif
for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) {
if(i > 0) ok(i - 1, j);
if(i < 2) ok(i + 1, j);
if(j > 0) ok(i, j - 1);
if(j < 2) ok(i, j + 1);
}
cin >> s >> t;
cnt[s] = 1;
que.push(s);
while(!que.empty()) {
now = que.front();
que.pop();
int p = now.find('.');
for(int i = 0; i < 9; ++i) if(tag[p][i]) bfs(p, i);
}
cout << -1;
return 0;
}