poj 3221 Diamond Puzzle (BFS)

来源:互联网 发布:数据库归档日志满了 编辑:程序博客网 时间:2024/05/29 04:46

给一个0~6组成的串,用特殊的变换方式,得出"0123456",只有0是空的

用的最原始的BFS,因为只有0~6几个字符,而且总的N<=5040,比较大,所以考虑从终点"0123456"开始搜索,预处理出每个状态的时间,然后O(1)的查询.



图中的数字,对应字符串的下标.

用d[i][j]表示当0处在i处时,它能和d[i][j]相交换!


#include<stdio.h>#include<map>#include<queue>#include<string>#include<string.h>#include<algorithm>using namespace std;struct node{    char s[10];    int t;};map<string,int>m;//用来存字符串状态是否已经被搜过.map<string,int>ans;//用来存每个字符串状态的答案.int n;char s[10];char S[10]="0123456";int d[8][5]={{2,4,6,-1},{2,6,-1},{0,1,3,-1},{2,4,-1},{0,3,5,-1},{4,6,-1},{0,1,5,-1}};void bfs(){    queue<node>q;    node vw,vn;    strcpy(vn.s,S);    vn.t=0;    m[S]=1;    q.push(vn);    while(!q.empty())    {        vn=q.front();        q.pop();        ans[vn.s]=vn.t;        int tag;        for(int i=0;i<7;i++)        {            if(vn.s[i]=='0')            {                tag=i;break;            }        }        for(int i=0;d[tag][i]!=-1;i++)        {            strcpy(vw.s,vn.s);            int ti=vn.t;            int t=d[tag][i];            char c=vw.s[tag];            vw.s[tag]=vw.s[t];            vw.s[t]=c;            string b=vw.s;            if(m[b]!=1)            {                    vw.t=ti+1;                    m[b]=1;                    q.push(vw);            }        }    }}int main(){    bfs();    scanf("%d",&n);    while(n--)    {        scanf("%s",s);        if(strcmp(S,s)==0)        printf("0\n");        else        printf("%d\n",ans[s]==0?-1:ans[s]);    }}