zoukankan      html  css  js  c++  java
  • 八数码(map版)

    八数码

    map真是个奇技淫巧好东西

    可以十分简单的实现hash,当然速度就不敢保证了

    因为九位数不算很大,完全可以用int存下,所以便将八数码的图像转换成一个int型的数字

    #include<iostream>
    #include<queue>
    #include<map>
    #include<algorithm>
    using namespace std;
    int d[4]={-3,-1,1,3};
    struct node
    {
        int position;//用0表示空位,position为0的位置 
        int h;//状态 
        int s;//步数 
    };
    int ten[11]={0,100000000,10000000,1000000,100000,10000,1000,100,10,1};//用于分离出某一格中的数字的数组 
    bool check(int p,int d)//判断是否合法。p是空位位置,d是移动个数 
    {
        if(p+d<=0)
            return false;
        if(p+d>9)
            return false;
        if(p%3==1&&d==-1)//空位在最左边一列而且向左移 
            return false;
        if(p%3==0&&d==1)//同上,左变为右 
            return false;
        return true;
    }
    queue<node>q;
    map<int,int> kkk;//用于hash的map 
    int main() 
    {
        cin.sync_with_stdio(false);
        int end;
        //cout<<kkk.count(1);
        cin>>end;//结束状态 
        if(end==123804765)//根据题目来的特判 
        {
            cout<<0;
            return 0;
        }
        node pass;//因为是广艘,用pass储存队首元素 
        pass.position=5;
        pass.h=123804765;
        pass.s=0;
        q.push(pass);
        while(!q.empty())
        {
            pass=q.front();
            q.pop();
            node k=pass;
            for(int i=0;i<4;i++)//扩展状态 
            {
                k=pass;
                /*kkk[k.h]=0;
                cout<<kkk[k.h];*/
                if(check(k.position,d[i]))
                {
                    int replace=k.h/ten[k.position+d[i]]%10;//取出要交换的数字 
                    k.h=k.h-replace*ten[k.position+d[i]]+replace*ten[k.position];//交换 
                    k.s++; 
                    k.position=k.position+d[i];//更改空位位置 
                    if(k.h==end) 
                    {
                        cout<<k.s;
                        return 0;
                    }
                    if(!kkk[k.h])//如果没有被扩展到,入队 
                    {
                        kkk[k.h]=1;
                        q.push(k);	
                    }
                }
            }
        }
    }
    
  • 相关阅读:
    (3.4)常用知识-char与varchar的选择
    (3.3)常用知识-索引使用、维护与填充因子
    (3.2)常用知识-字符串处理
    (3.1)常用知识-日期处理
    基于Sql Server 2008的分布式数据库的实践
    将expression转化为数据类型int时发生算术溢出错误
    webserver and application server
    web前端
    linkin
    jquery load
  • 原文地址:https://www.cnblogs.com/Lance1ot/p/8496212.html
Copyright © 2011-2022 走看看