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

    #include<cstring>
    #include<cstdlib>
    #include<cstdio>
    #include<cmath>
    #include<iostream>
    #include<map>
    #define N 510000
    using namespace std;
    struct node{
    int a[10],x;
    }p[N],tmp;
    map<int,bool> b;
    int ed=123804765,tail,ans[N];
    void bfs()
    {
    int t=0;
    tail=1;
    for(int i=1;i<=9;i++) t=t*10+p[1].a[i];
    b[t]=1;
    if(t==ed) {printf("0 ");return;}

    for(int i=1;i<=tail;i++)
    {
    int a[10],x;
    for(int j=1;j<=9;j++) a[j]=p[i].a[j];
    x=p[i].x;

    if(x>=4)
    {
    for(int j=1;j<=9;j++) tmp.a[j]=a[j];
    swap(tmp.a[x],tmp.a[x-3]);
    tmp.x=x-3;
    t=0;
    for(int j=1;j<=9;j++) t=t*10+tmp.a[j];
    if(b.count(t)==0)
    {
    b[t]=1;
    tail++;
    p[tail]=tmp;
    ans[tail]=ans[i]+1;
    if(t==ed) {printf("%d ",ans[tail]);return;}
    }
    }//上

    if(x<=6)
    {
    for(int j=1;j<=9;j++) tmp.a[j]=a[j];
    swap(tmp.a[x],tmp.a[x+3]);
    tmp.x=x+3;
    t=0;
    for(int j=1;j<=9;j++) t=t*10+tmp.a[j];
    if(b.count(t)==0)
    {
    b[t]=1;
    tail++;
    p[tail]=tmp;
    ans[tail]=ans[i]+1;
    if(t==ed) {printf("%d ",ans[tail]);return;}
    }
    }

    if(x!=1 && x!=4 && x!=7)
    {
    for(int j=1;j<=9;j++) tmp.a[j]=a[j];
    swap(tmp.a[x],tmp.a[x-1]);
    tmp.x=x-1;
    t=0;
    for(int j=1;j<=9;j++) t=t*10+tmp.a[j];
    if(b.count(t)==0)
    {
    b[t]=1;
    tail++;
    p[tail]=tmp;
    ans[tail]=ans[i]+1;
    if(t==ed) {printf("%d ",ans[tail]);return;}
    }
    }

    if(x!=3 && x!=6 && x!=9)
    {
    for(int j=1;j<=9;j++) tmp.a[j]=a[j];
    swap(tmp.a[x],tmp.a[x+1]);
    tmp.x=x+1;
    t=0;
    for(int j=1;j<=9;j++) t=t*10+tmp.a[j];
    if(b.count(t)==0)
    {
    b[t]=1;
    tail++;
    p[tail]=tmp;
    ans[tail]=ans[i]+1;
    if(t==ed) {printf("%d ",ans[tail]);return;}
    }
    }
    }
    }
    int main()
    {
    for(int i=1;i<=9;i++)
    {
    char c=getchar();
    p[1].a[i]=c-'0';
    if(c=='0') p[1].x=i;
    }
    bfs();
    return 0;
    }

  • 相关阅读:
    python 模块特点
    python 对象类型有哪些?
    python 异常处理
    python urllib2查询数据
    哈希表之词频统计
    泛型 队列
    大小端存储
    收藏 去掉 html 标签的perl 小函数
    好玩 多线程 显示
    服务器客户端 之 文件下载
  • 原文地址:https://www.cnblogs.com/liumengliang/p/11196049.html
Copyright © 2011-2022 走看看