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;
    }

  • 相关阅读:
    spl_autoload_register()和__autoload()区别
    编程语言相关科目
    类继承和重写的区别
    心理扭曲和心理变态含义分别是什么?
    java中的静态方法
    《深入理解JavaScript》—— JSON
    《深入理解JavaScript》—— Date
    《深入理解JavaScript》—— 正则表达式
    《深入理解JavaScript》—— 数组
    《深入理解JavaScript》—— 对象与继承(第2层)
  • 原文地址:https://www.cnblogs.com/liumengliang/p/11196049.html
Copyright © 2011-2022 走看看