首页 > 其他 > 详细

BFS八数码

时间:2020-04-09 19:30:54      阅读:70      评论:0      收藏:0      [点我收藏+]

BFS八数码问题:

#include <iostream>
#include <cstring>
#include <queue>
#include <unordered_map>
using namespace std;

int bfs(string start)
{
    string end = "12345678x";
    queue<string> q;
    unordered_map<string, int>d;
    q.push(start);
    d[start] = 0;
    int dx[4] = {-1,1,0,0},dy[4] = {0,0,1,-1};
    while(!q.empty())
    {
        string s = q.front();
        q.pop();
        int distance = d[s];
        if(s == end) return distance;
        int k = s.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(s[k],s[a*3+b]);
                if(!d.count(s))
                {
                    d[s] = distance + 1;
                    q.push(s);
                }
                swap(s[k],s[a*3+b]);
            }
        }
        
    }
    
    return -1;
}
int main()
{
    string start;
    cin>>start;
    cout<<bfs(start)<<endl;
}

 

BFS八数码

原文:https://www.cnblogs.com/longxue1991/p/12668986.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!