社区讨论
求条10pts
P1379八数码难题参与者 1已保存回复 1
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 1 条
- 当前快照
- 1 份
- 快照标识符
- @mivsaa08
- 此快照首次捕获于
- 2025/12/07 21:54 2 个月前
- 此快照最后确认于
- 2025/12/10 22:35 2 个月前
CPP
#include <bits/stdc++.h>
using namespace std;
string start;
string gay = "123804765";
map<string, bool> vis;
struct node {
string a; int st;
}tmp;
queue<node> q;
void solve(node vct) {
string s = vct.a; int stp = vct.st;
for (int i = 0; i < 9; i ++) {
if (s[i] == '0') {
if (i >= 3 && i <= 8) {
swap(s[i], s[i - 3]);
if (vis[s]) {
swap(s[i], s[i - 3]);
continue;
}
vis[s] = 1;
node t;
t.a = s;
t.st = stp + 1;
q.push(t);
swap(s[i], s[i - 3]);
}
if (i >= 0 && i <= 5) {
swap(s[i], s[i + 3]);
if (vis[s]) {
swap(s[i], s[i + 3]);
continue;
}
vis[s] = 1;
node t;
t.a = s;
t.st = stp + 1;
q.push(t);
swap(s[i], s[i + 3]);
}
if (i % 3 == 1 || i % 3 == 2) {
swap(s[i], s[i - 1]);
if (vis[s]) {
swap(s[i], s[i - 1]);
continue;
}
vis[s] = 1;
node t;
t.a = s;
t.st = stp + 1;
q.push(t);
swap(s[i], s[i - 1]);
}
if (i % 3 == 0 || i % 3 == 1) {
swap(s[i], s[i + 1]);
if (vis[s]) {
swap(s[i], s[i + 1]);
continue;
}
vis[s] = 1;
node t;
t.a = s;
t.st = stp + 1;
q.push(t);
swap(s[i], s[i + 1]);
}
break;
}
}
return;
}
void bfs() {
tmp.a = start;
tmp.st = 0;
q.push(tmp);
vis[start] = 1;
while (q.size()) {
node vct = q.front();
q.pop();
if (vct.a == gay) {
cout << vct.st << '\n';
exit(0);
}
solve(vct);
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> start;
if (start == gay) {
cout << "0\n";
return 0;
}
bfs();
return 0;
}
调不动了
回复
共 1 条回复,欢迎继续交流。
正在加载回复...