蓝桥杯 [九宫重排]
题目:
思路:
以字符串的形式记录每一次的状态,从初始状态开始,把每一次没有遇到过的状态加入队列,再次进行下一次搜索,直到第一次遇到与结束位置一样的就是我们要找的最短次数
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll MAX = 1e5 + 5;
string Head;//开始位置
string End;//结束位置
typedef struct AA {
string val;
int x;
int y;//空位的位置
int sum;
};
queue<AA> q;//队列 广搜
map<string, int> m;// 去重
int val = -1;
string Map_str(string a, int x, int y, int tx, int ty) {
string b = a;
b[x * 3 + y] = a[tx * 3 + ty];
b[tx * 3 + ty] = a[x * 3 + y];
return b;
}
void bfs(AA a) {
if (a.val == End) {
val = a.sum;
return;
}
if (m[a.val] == 0) {
m[a.val] = 1;
} else {
return;
}
int mark[][2] = {{1, 0},
{-1, 0},
{0, 1},
{0, -1}};
for (int i = 0; i < 4; i++) {
int tx = a.x + mark[i][0];
int ty = a.y + mark[i][1];
if (tx >= 0 && tx < 3 && ty >= 0 && ty < 3) {
AA t;
t.x = tx;
t.y = ty;
t.val = Map_str(a.val, a.x, a.y, tx, ty);
t.sum = a.sum + 1;
if (m[t.val] == 0) {
q.push(t);
}
}
}
}
int main() {
cin >> Head;
cin >> End;
AA t;
t.val = Head;
t.sum = 0;
for (int i = 0; i < 9; i++) {
if (Head[i] == '.') {
t.x = i / 3;
t.y = i % 3;
break;
}
}
q.push(t);
while (q.size() && val == -1) {
AA a = q.front();
q.pop();
bfs(a);
}
cout << val << endl;
return 0;
}