solution.cpp 788 字节
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
#include <unordered_map>
#include <queue>
using namespace std;

int dir[] = {1, -1, 2, -2};
unordered_map<string, int> dist;
string S = "12345678X", T = "87654321X";

int bfs()
{
    queue<string> q;
    q.push(S);
    dist[S] = 0;

    while (q.size())
    {
        string t = q.front();
        q.pop();

        if (t == T)
            return dist[t];

        int k = t.find('X'), distance = dist[t];
        for (int i = 0; i < 4; i++)
        {
            swap(t[k], t[(k + dir[i] + 9) % 9]);
            if (!dist.count(t))
            {
                q.push(t);
                dist[t] = distance + 1;
            }
            swap(t[k], t[(k + dir[i] + 9) % 9]);
        }
    }

    return -1;
}

int main()
{
    cout << bfs() << endl;
    return 0;
}