六数码noj
现有一两行三列的表格如下:
A B C
D E F
把1、2、3、4、5、6六个数字分别填入A、B、C、D、E、F格子中,每个格子一个数字且各不相同。每种不同的填法称为一种布局。如下:
1 3 5
2 4 6
布局1
2 5 6
4 3 1
布局2
定义α变换如下:把A格中的数字放入B格,把B格中的数字放入E格,把E格中的数字放入D格,把D格中的数字放入A格。
定义β变换如下:把B格中的数字放入C格,把C格中的数字放入F格,把F格中的数字放入E格,把E格中的数字放入B格。
问:对于给定的布局,可否通过有限次的α变换和β变换变成下面的目标布局:
1 2 3
4 5 6
目标布局
输入:
本题有多个测例,每行一个,以EOF为输入结束标志。每个测例的输入是1到6这六个数字的一个排列,空格隔开,表示初始布局ABCDEF格中依次填入的数字。
输出:
每个输出占一行。可以转换的,打印Yes;不可以转换的,打印No。
输入样例:
1 3 5 2 4 6
2 5 6 4 3 1
输出样例:
No
Yes
#include<iostream>
#include<queue>
using namespace std;
//六数码问题
struct Node {
int num[6];/*各位数*/
int value;
};
int used[654322];
Node start;
queue<Node>q1;
void setValue(Node&);
bool bfs();
Node transform(Node,int);
int main()
{
while (cin >> start.num[0])
{
for (int i = 1; i < 6; i++) {
cin >> start.num[i];
}
setValue(start);
//初始归零
for (int i = 123456; i < 654322; i++) {
used[i] = 0;
}
while (!q1.empty()) q1.pop();//注意清空栈 bfs过程中如果提前return情况 栈不会清空
if (bfs()) {
cout << "Yes" << endl;
}
else cout << "No" << endl;
}
return 0;
}
void setValue(Node& s)
{//先乘以10再加个位
s.value = 0;
for (int i = 0; i < 6; i++) {
s.value *= 10;
s.value += s.num[i];
}
}
bool bfs()
{
Node now, next;
q1.push(start);
used[start.value] = 1;
while (!q1.empty()) {
now = q1.front();
q1.pop();
for (int i = 0; i < 2; i++) {
next = transform(now, i);
if (!used[next.value]){
used[next.value] = 1;
if (next.value == 123456)return true;
else q1.push(next);
}
}
}
return false;
}
Node transform(Node now,int i)
{
Node next;
switch (i) {
case 0:
{
next.num[0] = now.num[3];//D->A
next.num[1] = now.num[0];//A->B
next.num[2] = now.num[2];
next.num[3] = now.num[4];//E->D
next.num[4] = now.num[1];//B->E
next.num[5] = now.num[5];
break;
}
case 1:
{
next.num[0] = now.num[0];
next.num[1] = now.num[4];//E->B
next.num[2] = now.num[1];//B->C
next.num[3] = now.num[3];
next.num[4] = now.num[5];//F->E
next.num[5] = now.num[2];//C->F
break;
}
}
setValue(next);
return next;
}