八数码


想了好久,终于出来了

先贴个代码,回来再写





#include <iostream>
#include<queue>
#include<cstdio>
#define N 9
using namespace std;

const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
int vis[400000]= {0}, fact[9];
struct  node
{
    int eight[N];
    int num;
    int dist=0;
}intial,last,temp;

queue<node> Q;
void prin(node *p)
{
    for(int i=0; i<N; i++)
        printf("%d ",p->eight[i]);
    printf("\n");
}

void fac()
{
    fact[0] = 1;
    for(int i = 1; i < N; i++) fact[i] = fact[i-1] * i;
}

void change(node &t)
{
    t.num=0;
    for(int i = 0; i < 9; i++)
    {
        int cnt = 0;
        for(int j = i+1; j < 9; j++)
            if(t.eight[j] < t.eight[i])
              cnt++;
     //   printf("change %d %d %d ",t.num,fact[8-i],cnt);
        t.num += fact[8-i] * cnt;
       // printf("   %d\n",t.num);

    }
   // printf("\n");
}
int  bfs()
{
    while(!Q.empty())
        Q.pop();
    if(intial.num==last.num)
       return 0;
    Q.push(intial);
    while(!Q.empty())
    {
        int z;
        for(z = 0; z < N; z++)
            if(!Q.front().eight[z])
                break;
        int x = z/3, y = z%3;
        //printf("\n");
       // prin(&Q.front());
      //  printf("front : %d %d %d\n\n",Q.front().num,Q.front().dist,vis[Q.front().num]);
        for(int d = 0; d < 4; d++)
        {
            temp=Q.front();
            int newx = x + dx[d];
            int newy = y + dy[d];
            int newz = newx * 3 + newy;
           // prin(&temp);
           // printf("   poi : %d %d %d %d\n",newx,newy,newz,vis[temp.num]);
            if(newx >= 0 && newx < 3 && newy >= 0 && newy < 3)
            {
                temp.eight[z]=Q.front().eight[newz];
                temp.eight[newz]=Q.front().eight[z];
                temp.dist=Q.front().dist+1;
              change(temp);
              if(!vis[temp.num])
              {
                  // prin(&temp);
               // printf("temp : %d %d %d\n",temp.num,temp.dist,vis[temp.num]);
                if(temp.num==last.num)
                    return temp.dist;
                vis[temp.num]=1;
                Q.push(temp);
              }
            }
        }
        Q.pop();
    }
}

int main()
{
    freopen("input.txt","r",stdin);
    int i;
    fac();
    for(i=0; i<N; i++)
        intial.eight[i]=N-i;
    for(i=0; i<N; i++)
        scanf("%d",&intial.eight[i]);
    for(i=0; i<N; i++)
        scanf("%d",&last.eight[i]);
    change(intial);
    change(last);
    //bfs();
   // prin(&intial);
   // prin(&last);
    // printf("last : %d %d %d\n",last.num,last.dist,vis[last.num]);
    // printf("intial : %d %d %d\n",intial.num,intial.dist,vis[intial.num]);
    printf("%d\n",bfs());
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值