[搜索] hdu1043 Eight(8思路)

来源:互联网 发布:矩阵论清华大学出版社 编辑:程序博客网 时间:2024/06/05 14:33

思路来源:八数码的八境界

境界一:广搜+map

最简单的思路,从输入的字符串开始暴力广搜,用map记录到达每种状态的步骤以及是否搜索过,然后爆了内存.

#include<bits/stdc++.h>using namespace std;char c[10];string s,wt="123456789";map<string,string>mp;int dx[]={0,0,-1,1};int dy[]={1,-1,0,0};void bfs(){    queue< pair<string,int> >q;    int k;    for(int i=0;i<9;i++)    {        if(s[i]=='9') k=i;    }    q.push(make_pair(s,k));    if(s==wt) {puts("");return ;}    while(!q.empty())    {        pair<string,int>p=q.front();        q.pop();        if(p.first==wt) break;        int x=p.second/3;        int y=p.second%3;        for(int i=0;i<4;i++)        {            int tx=x+dx[i];            int ty=y+dy[i];            if(tx<0||tx>=3||ty<0||ty>=3) continue;            string ts=p.first;            swap(ts[x*3+y],ts[tx*3+ty]);            //cout<<p.first<<" "<<ts<<" "<<i<<endl;            if(mp[ts]!="") continue;            string ns=mp[p.first];            if(i==0) ns+='u';            else if(i==1) ns+='r';            else if(i==2) ns+='d';            else if(i==3) ns+='l';            q.push(make_pair(ts,tx*3+ty));            mp[ts]=ns;        }    }    if(mp[wt]=="") printf("unsolvable");    else    {        cout<<mp[wt]<<endl;    }}int main(){    while(~scanf("%s",c))    {        s="";        if(c[0]!='x') s+=c[0];            else s+='9';        for(int i=0;i<8;i++)        {            scanf("%s",c);            if(c[0]!='x') s+=c[0];            else s+='9';        }        //cout<<s<<endl;        mp.clear();        bfs();    }    return 0;}
原创粉丝点击