其他分享
首页 > 其他分享> > 九宫格

九宫格

作者:互联网

 

终于写出一道A*

#include<bits/stdc++.h>

using namespace std;

int n,x;

string jik;

map <string ,bool> ji;

struct node

{

         string a;int b,jih,jil,ma;

};

priority_queue<node>a;node kai;

bool operator <(node a,node b){

         if(a.b!=b.b)

         return a.b>b.b;

         return a.ma>b.ma;

}

int tu[2][10],jjh[4]={-1,0,0,1},jjl[4]={0,-1,1,0},bian[4]={-3,-1,1,3};

int biao[5][5];

void dabiao()

{

         tu[0][1]=0;tu[0][2]=0;tu[0][3]=0;tu[0][4]=1;tu[0][5]=1;tu[0][6]=1;

         tu[0][7]=2;tu[0][8]=2;tu[0][0]=2;

         tu[1][1]=0;tu[1][2]=1;tu[1][3]=2;tu[1][4]=0;tu[1][5]=1;tu[1][6]=2;

         tu[1][7]=0;tu[1][8]=1;tu[1][0]=2;

}

int suan(string a)

{

         int ans=0;

         for(int i=0;i<3;i++)

         {

                   for(int j=0;j<3;j++)

                   {

                            ans=ans+abs(tu[0][a[i*3+j]-'0']-i)+abs(tu[1][a[i*3+j]-'0']-j);

                   }

         }       

         return ans;

}

void bfs()

{

         while(a.empty()==0)

         {

                   kai=a.top();a.pop();

                   if(kai.a=="123456780")

                   {

                            cout<<kai.b;

                            return;

                   }

                   for(int i=0;i<4;i++)

                   {

                            int h=kai.jih+jjh[i],l=kai.jil+jjl[i];

                            if(h>=0&&h<3&&l>=0&&l<3)

                            {

                                     swap(kai.a[kai.jih*3+kai.jil],kai.a[kai.jih*3+kai.jil+bian[i]]);

                                     if(ji[kai.a]==0)

                                     {

                                               ji[kai.a]=1;

                                               node jikai;

                                               jikai=kai;

                                               jikai.ma=suan(kai.a);

                                               jikai.jih=h;jikai.jil=l;jikai.b=kai.b+1;

                                               a.push(jikai);

                                     }

                                     swap(kai.a[kai.jih*3+kai.jil],kai.a[kai.jih*3+kai.jil+bian[i]]);

                            }

                   }

         }

}

int main()

{

         dabiao();

    for(int i=0;i<3;i++)

    {

        for(int j=0;j<3;j++)

        {

            cin>>x;

            jik=jik+char(x+'0');

            if(x==0)

            {

                kai.jih=i;kai.jil=j;

            }

        }

    }

    kai.ma=suan(jik);

    kai.a=jik;kai.b=0;

    a.push(kai);

    ji[jik]=1;

    bfs();

}

标签:九宫格,int,kai,tu,jikai,jih,jil
来源: https://www.cnblogs.com/fanhao050109/p/10961355.html