搜索 Seven Puzzle (AOJ 0121 bfs)

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<map>
#include<iostream>
#include<queue>
using namespace std;
map<string,int>gmap;
int a[2][4];
int b[2][4];
int vis[4][2]={1,0,0,1,0,-1,-1,0};
struct text
{
    int a[2][4];
}st,tt,start;
queue<text> q;
char s[9];
char ss[9];
int temp=0;
int cnt=1;
bool check(int x,int y)
{
    if(x<0||y<0||x>=2||y>=4)
        return false;
    return true;
}
void bfs()
{
    while(!q.empty())
    {
        st=q.front();
        q.pop();
        int x,y;
        for(int i=0;i<2;i++)
        {
            for(int j=0;j<4;j++)
            {
                if(st.a[i][j]==0)
                {
                   x=i;
                   y=j;
                }
                a[i][j]=st.a[i][j];
                ss[i*4+j]=st.a[i][j]+'0';
            }

        }
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<2;j++)
            {
                int k=x+vis[i][0];
                int l=y+vis[i][1];
                if(check(k,l))
                {
                    int xx=a[x][y];
                    a[x][y]=a[k][l];
                    a[k][l]=xx;
                    for(int i=0;i<2;i++)
                    {
                        for(int j=0;j<4;j++)
                        {
                            s[i*4+j]=a[i][j]+'0';
                            tt.a[i][j]=a[i][j];
                        }
                    }
                    s[8]='\0';
                    if(!gmap[s]>0)
                    {
                        gmap[s]=gmap[ss]+1;
                        q.push(tt);
                    }
                    xx=a[x][y];
                    a[x][y]=a[k][l];
                    a[k][l]=xx;
                }
            }
        }
    }
}
int main()
{
    for(int i=0;i<8;i++)
        a[i/4][i%4]=i;
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<4;j++)
            start.a[i][j]=a[i][j];
    }
    for(int i=0;i<2;i++)
        {
            for(int j=0;j<4;j++)
            {
                s[i*4+j]=start.a[i][j]+'0';
            }
        }
    s[8]='\0';
    gmap[s]=1;
    q.push(start);
    bfs();//预处理 将结果用map<string,int >存储
    while(~scanf("%d",&a[0][0]))
    {
        for(int i=1;i<4;i++)
            scanf("%d",&a[0][i]);
        for(int i=0;i<4;i++)
            scanf("%d",&a[1][i]);
        for(int i=0;i<2;i++)
        {
            for(int j=0;j<4;j++)
            {
                s[i*4+j]=a[i][j]+'0';
            }
        }
        s[8]='\0';
       // puts(s);
        printf("%d\n",gmap[s]-1);
    }
}

你可能感兴趣的:(搜索 Seven Puzzle (AOJ 0121 bfs))