九数码

Problem Description
Nine tiles, each with a number from 1 to 9 on it, are packed into a 3 by 3 frame. Your task is to arrange the tiles so that they are ordered as 
1 2 3
4 5 6
7 8 9
At each step, you can do the following operation to the tiles: Choose 2 by tiles, rotate the tiles in clockwise order. For example:
1 2 3-->4 1 3
4 5 6-->5 2 6
7 8 9-->7 8 9
or
1 2 3-->1 2 3
4 5 6-->4 8 5
7 8 9-->7 9 6
Write a program to find the minimum number of steps.
Input
Input contains multiple test cases.
each test case is a description of a configuration of the nine tiles. The description is just a list of the tiles in there initial positions, with the rows listed from top to bottom, and from left to right within a row, where the tiles are represented by numbers 1 to 9. For example:
9 8 7
6 5 4
3 2 1
is described by this list:
9 8 7 6 5 4 3 2 1
Output
Output the minimum number of steps on a single line for each test case.
Sample Input
1 2 3 4 5 6 7 8 9
4 1 3 5 2 6 7 8 9
Sample Output
0
3
//关键字:康拓展开
//标程:<pre name="code" class="html">#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
    char a[9];
    int step;
}q[370000];
int  ans[370000];
int c[8] = {1,2,6,24,120,720,5040,40320};
int s[4][9]={{1,4,2,0,3,5,6,7,8},{0,2,5,3,1,4,6,7,8},{0,1,2,4,7,5,3,6,8},{0,1,2,3,5,8,6,4,7}};
int kangtuo(node &tmp)
{
    int ret = 0;
    for(int i = 0; i < 8; ++ i)
        for(int j = i+1; j < 9; ++ j)
          if(tmp.a[i] > tmp.a[j]) ret += c[7-i];
    return ret;
}
void fun()
{
    node tmp;
    for(int i = 0; i < 9; ++ i) tmp.a[i] = '0'+i;
    tmp.step = 0;
    memset(ans,-1,sizeof(ans));
    ans[kangtuo(tmp)] = 0;
    int head = -1,last = 0;
    q[0] = tmp;
    while(head ++ < last)
    {
        tmp = q[head];
        node tp;
        tp.step = tmp.step + 1;
        for(int i = 0; i < 4; ++ i)
        {
            for(int j = 0; j < 9; ++ j)
                tp.a[j] = tmp.a[s[i][j]];
            int k = kangtuo(tp);
            if(ans[k] < 0)
            {
                ans[k] = tp.step;
                q[++last] = tp;
            }
        }
    }
}
int main()
{
//    freopen("a.txt","r",stdin);
    fun();
    int x;
    while(scanf("%d",&x)!=EOF)
    {
        node tmp;
        tmp.a[0] = x;
        for(int i = 1; i < 9; ++ i)
        {
            scanf("%d",&x);
            tmp.a[i] = x;
        }
        printf("%d\n",ans[kangtuo(tmp)]);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值