四数码问题

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


int dx[4]={0, 0, 1, -1};
int dy[4]={1,-1,0 , 0};

struct node{
    string state;
    int t;

};

int bfs(const string &state,const string &traget)
{
    set<string>jude;//里面的元素不能重复;
    queue<node>q;
    q.push({state, 0});//给以个结构其变量赋值,并把它加如队列;
    jude.insert(state);//增加一个元素

    while(q.size())
    {
        node cur = q.front();q.pop();
        if(cur.state == traget) return cur.t;
        int  s = cur.state.find('0');//找到课移动图的位置
        int dix = s/2;//将一维数组的做标转化为二维数组方便后序操作
        int diy = s%2;
        for(int i=0;i<4;i++)
        {
            int sx = dix + dx[i];
            int sy = diy + dy[i];

            node nextcur = cur;
            nextcur.t++;
            int s2 = sx*2 +sy;//还原为一维数组坐标,用于后面
            if(sx >= 0 && sx < 2 && sy >= 0 && sy <2)//判断是否越界
            {
                swap(nextcur.state[s2],nextcur.state[s]);
                if(!jude.count(nextcur.state)){//判断避免与前面的法生重复
                    jude.insert(nextcur.state);//加如以移动后的状态,余下一次对比因为以个点课以像四个方向运动,这样做是为了避免以动了有以会去;减少不比要的步骤,个人认为相当于剪枝;
                    q.push(nextcur);//加入队列
                }
            }

        }
    }
    return -1;


}


int main()
{
    int a[4],b[4];
    string state, traget;
    for(int i=0;i<4;i++)//将变为字符串个人认为字符串好处理
    {
        cin >> a[i];
        char c = a[i]+'0';
        state+=c;
    }
    for(int i=0;i<4;i++)
    {
        cin >> b[i];
        char c = b[i]+'0';
        traget+=c;
    }
    cout << bfs(state,traget);


}

追求吾之所爱
原文地址:https://www.cnblogs.com/rstz/p/12393218.html