八数码难题TLE,只有10pts,求调
查看原帖
八数码难题TLE,只有10pts,求调
607952
ZHANGGUIZHI楼主2024/11/1 14:45
#include<bits/stdc++.h>

using namespace std;
int start;
int a[5][5];
int dx[] = { -1 , 0 , 1 , 0 };
int dy[] = { 0 , -1 , 0 , 1 };
struct node {
    int stage, step;
}
t[1000002];
void pre(int x) {
    for (int i = 3; i >= 1; i--)
        for (int j = 3; j >= 1; j--) {
            a[i][j] = x % 10;
            x /= 10;
        }
}
int rev() {
    int ans = 0;
    for (int i = 1; i <= 3; i++)
        for (int j = 1; j <= 3; j++) {
            ans += a[i][j];
            ans *= 10;
        }
    return ans;
}
map < int, bool > vis;
int bfs() {
    queue < node > q;
    q.push((node) {
        start,
        0
    });
    while (!q.empty()) {
        node s = q.front();
        int x = s.stage;
        pre(x);
        if (x == 123804765) return s.step;
        int ii, jj;
        for (ii = 1; ii <= 3; ii++) {
            for (jj = 1; jj <= 3; jj++)
                if (!a[ii][jj]) break;
            if (!a[ii][jj]) break;
        }
        for (int i = 0; i < 4; i++) {
            int xx = ii + dx[i], yy = jj + dy[i];
            if (xx > 3 || xx < 1 || yy > 3 || yy < 1) continue;
            swap(a[ii][jj], a[xx][yy]);
            int p = rev();
            if (!vis[p]) {
                vis[p] = 1, q.push((node) {
                    p,
                    s.step + 1
                });
            }
            swap(a[ii][jj], a[xx][yy]);
        }
    }
    return -1;
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> start;
    cout << bfs() << '\n';
    return 0;
}
2024/11/1 14:45
加载中...