A* 69pts毫无头绪,求调!!
查看原帖
A* 69pts毫无头绪,求调!!
22716
神仙酱楼主2024/3/27 21:35
#include <algorithm>
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;

using PIS = pair<int, string>;
const string target = "123804765";
string start;
int h(string str) {
    int res = 0;
    for (int i = 0; i < 9; i++) {
        if (target[i] != str[i] && str[i] != '0')
            res++;
    }
    return res;
}

int bfs() {
    priority_queue<PIS, vector<PIS>, greater<PIS>> q;
    unordered_map<string, int> dist;
    q.emplace(h(start), start);
    dist[start] = 0;
    int dx[] = { 1, -1, 0, 0 }, dy[] = { 0, 0, 1, -1 };
    while (q.size()) {
        auto t = q.top();
        q.pop();
        const string src = t.second;
        int px = src.find('0') / 3, py = src.find('0') % 3;
        for (int i = 0; i < 4; ++i) {
            int x = px + dx[i], y = py + dy[i];
            if (x < 0 || x >= 3 || y < 0 || y >= 3)
                continue;
            string st = src;
            swap(st[x * 3 + y], st[px * 3 + py]);
            if (!dist.count(st) || dist[st] > dist[src] + 1) {
                dist[st] = dist[src] + 1;
                if (st == target)
                    return dist[st];
                q.emplace(t.first + h(st), st);
            }
        }
    }
    return -1;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen(".in", "r", stdin);
    // freopen(".out", "w", stdout);
#else
    cin.tie(0)->sync_with_stdio(0);
#endif
    cin >> start;
    cout << bfs();
    return 0;
}

2024/3/27 21:35
加载中...