UVA10422八个方向图形状态搜素

本文分享了一种解决特定滑块谜题的算法实现过程,通过DFS深度优先搜索结合状态记录的方法,在限定步数内找到解决方案。代码使用C++编写,并详细展示了如何处理状态转移及避免重复状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这题其实一开始我写的代码稍微改下就能过,浪费了好长时间,发现超过十步的判断要写在for循环里面,不然会WA,

后来想了一下,应该是写在外面状态数太多,存不下会导致WA,改一下就行了。这么写时间稍微长些,但是代码简单。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<set>
using namespace std;
const int MAX=1e7+10;

set<string> vis;
struct state
{
    string s;
    int d;
}st[MAX];
int x[8]={-11,-9,-7,3,9,11,-3,7};
string s="111110111100 110000100000",ss;
/*int t_insert(string s)
{
    int ans=0;
    for(int i=0;i<25;i++)
    {
        ans*=2;
        if(s[i]=='1')
            ans+=1;
        if(s[i]==' ')
            ans-=1;
    }
    ans=ans*2+1;
    if(vis.count(ans)) return 0;
    vis.insert(ans);
    return 1;
}*/
void dfs()
{
    int fr=1,re=2;
    st[1].s=ss;
    st[1].d=0;
    vis.insert(ss);
    while(fr<re)
    {
       // cout<<"hehe"<<endl;
        int i=0;
        while(st[fr].s[i]!=' ') i++;
         if(st[fr].s==s)
         {
               cout<<"Solvable in "<<st[re].d<<" move(s)."<<endl;
               return;
         }
       // if(st[fr].s==s) return fr;
        for(int j=0;j<8;j++)
        {
               int tt=i+x[j];
               if(tt>=0&&tt<25)
               {
                    st[re].s=st[fr].s;
                    st[re].s[i]=st[fr].s[tt];
                    st[re].s[tt]=st[fr].s[i];
                    st[re].d=st[fr].d+1;
                    if(!vis.count(st[re].s))
                    {
                        if(st[re].d>10)
                        {
                            cout<<"Unsolvable in less than 11 move(s)."<<endl;
                            return;
                        }
                       // cout<<st[re].s<<endl;
                        if(st[re].s==s)
                        {
                            cout<<"Solvable in "<<st[re].d<<" move(s)."<<endl;
                            return;
                        }
                        vis.insert(st[re].s);
                       // if(st[re].d==10&&st[re].s==s) return re;
                        re++;
                    }
               }
        }
            fr++;
    }
   // return 0;
}
int main()
{
    int t;
    cin>>t;
    getchar();
    while(t--)
    {
       // memset(st,0,sizeof(st));
        ss="";
        string s1;
        for(int i=1;i<=5;i++)
        {
            getline(cin,s1);
            ss+=s1;
        }
      // cout<<ss<<endl;
        vis.clear();
       dfs();
       // if(temp == 0) printf("Unsolvable in less than 11 move(s).\n");
       // else printf("Solvable in %d move(s).\n", st[temp].d);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值