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

  • 相关阅读:
    行星工单系统部分实现(1)-流程控制
    当初要是看了这篇,React高阶组件早会了
    健壮高效的小程序登录方案
    SQL Case when 的使用
    JS脚本动态给元素/控件添加事件
    VMware虚拟机屏幕大小只有400,800怎么办如何解决
    mysql和mysql jdbc连接器mysql-connector-java对应关系
    mysql中难以理解的sql
    PLSQL计算质数
    java alibaba fastJson 遍历数组json
  • 原文地址:https://www.cnblogs.com/liumengliang/p/11196049.html
Copyright © 2011-2022 走看看