1150. 简单魔板
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB , Special Judge
Description
魔板由8个大小相同方块组成,分别用涂上不同颜色,用1到8的数字表示。
其初始状态是
1 2 3 4
8 7 6 5
对魔板可进行三种基本操作:
A操作(上下行互换):
8 7 6 5
1 2 3 4
B操作(每次以行循环右移一个):
4 1 2 3
5 8 7 6
C操作(中间四小块顺时针转一格):
1 7 2 4
8 6 3 5
用上述三种基本操作,可将任一种状态装换成另一种状态。Input
输入包括多个要求解的魔板,每个魔板用三行描述。
第一行步数N(不超过10的整数),表示最多容许的步数。
第二、第三行表示目标状态,按照魔板的形状,颜色用1到8的表示。
当N等于-1的时候,表示输入结束。Output
对于每一个要求解的魔板,输出一行。
首先是一个整数M,表示你找到解答所需要的步数。接着若干个空格之后,从第一步开始按顺序给出M步操作(每一步是A、B或C),相邻两个操作之间没有任何空格。
注意:如果不能达到,则M输出-1即可。Sample Input
45 8 7 64 1 2 338 7 6 51 2 3 4-1
Sample Output
2 AB
1 A
广度优先搜索魔板状态空间树。将初始态作为树的根,每个不同的状态作为不同的节点,操作的次数作为树的层次,则可得到第m步操作的后的所有状态的集合,也就是状态空间树,对该树进行广度优先搜索,按条件搜索到目标状态即可。没有采取任何优化方法,暴力求解。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct status
{
string up,down; // 表示魔板的上下两行
string op; // 表示从初始态到此状态的操作序列
}begin, target;
status operation(struct status curr, int operation)
{
struct status next=curr;
//A操作:上下行互换
if(operation == 1)
{
string tmp = next.up;
next.up = next.down;
next.down = tmp;
next.op = next.op+"A";
}
//B操作:行循环右移一个
if(operation == 2)
{
char a=next.up[3];
char b=next.down[3];
for(int i=3; i>0; i--)
{
next.up[i] = next.up[i-1];
next.down[i] = next.down[i-1];
}
next.up[0] = a;
next.down[0] = b;
next.op = next.op+"B";
}
//C操作:中间四小块顺时针转一格
if(operation == 3)
{
char tmp = next.up[1];
next.up[1] = next.down[1];
next.down[1] = next.down[2];
next.down[2] = next.up[2];
next.up[2] = tmp;
next.op = next.op+"C";
}
return next;
}
//判断两个转态是否相等
bool is_match(struct status a, struct status b)
{
return (a.up==b.up && a.down==b.down);
}
// 利用广度优先进行对状态序列树进行扫描
void bfs(int max)
{
if(is_match(begin,target) )
{
cout<<0<<endl;
return;
}
queue<struct status> q;
q.push(begin);
while(!q.empty())
{
struct status curr = q.front();
q.pop();
if(curr.op.size() > max)
{
cout<<-1<<endl;
return ;
}
if(is_match(curr, target) )
{
cout<<curr.op.size()<<" "<<curr.op<<endl;
return;
}
for(int i=1; i<4; i++)
{
struct status next;
next = operation(curr, i);
q.push(next);
}
}
}
int main()
{
int n;
while(cin>>n && n!=-1)
{
begin.up = "1234";
begin.down = "8765";
begin.op = "";
char tmp;
target.up = "1234";
target.down = "8765";
for(int i=0; i<4; i++)
{
cin>>tmp;
target.up[i] = tmp;
}
for(int i=0; i<4; i++)
{
cin>>tmp;
target.down[i] = tmp;
}
target.op = "";
bfs(n);
}
// system("pause");
return 0;
}