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;
}
九数码
最新推荐文章于 2019-08-17 10:31:24 发布