算法.bfs八数码

算法.bfs八数码_第1张图片

#include
#include
#include
#include
#include
using namespace std;
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,-1,1 };
int bfs(string state)
{
    queueq;
    unordered_mapd;
    q.push(state);
    d[state] = 0;
    while (q.size())
    {
        auto t = q.front();

        int dis = d[t];
        int k = t.find('x');
        int x = k / 3, y = k % 3;

        q.pop();
        string end = "12345678x";
        if (t == end)return d[t];
        for (int i = 0; i < 4; i++)
        {
            int a = x + dx[i], b = y + dy[i];
            if (a >= 0 && a < 3 && b >= 0 && b < 3)
            {
                swap(t[a * 3 + b], t[k]);
                if (!d.count(t))
                {
                    d[t] = dis + 1;
                    q.push(t);
                }
                swap(t[a * 3 + b], t[k]);
            }
            
        }
    }
    
    return -1;
}

int main()
{
    string state;
    for (int i = 0; i < 9; i++)
    {
        char s;
        cin >> s;
        state += s;
    }
    cout << bfs(state);
    return 0;
}

你可能感兴趣的:(宽度优先,算法)