2023-8-30 八数码(BFS)

题目链接:八数码
2023-8-30 八数码(BFS)_第1张图片

#include 
#include 
#include 
#include 

using namespace std;

int bfs(string start)
{
    string end = "12345678x";
    queue q;
    unordered_map d;
    q.push(start);
    d[start] = 0;
    
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        int distance = d[t];
        if(t == end) return distance;
        
        int k = t.find('x');
        int x = k / 3, y = k % 3;
        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[k], t[a * 3 + b]);
                if(!d.count(t))
                {
                    d[t] = distance + 1;
                    q.push(t);
                }
                swap(t[k], t[a * 3 + b]);
            }
        }
        
    }
    return -1;
    
}

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

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