各一个2x4的字符数组,有三种不同的操作,要求使用最少的操作,从“12345678”,转换成目标字符,输出最少步数,以及操作次序。
对C++类库的用法还是不够熟啊。
/*
ID: modengd1
PROG: msquare
LANG: C++
*/
#include <iostream>
#include <stdio.h>
#include <queue>
#include <map>
#include <string>
using namespace std;
struct node
{
int step;
string sta,ans;
};
map<string,bool> vis;
void opA(node &N)
{
N.step++;
N.ans.push_back(‘A‘);
for(int i=0;i<4;i++)
{
swap(N.sta[i],N.sta[i+4]);
}
}
void opB(node &N)
{
N.step++;
N.ans.push_back(‘B‘);
char temp=N.sta[3];
for(int i=3;i>0;i--)
{
N.sta[i]=N.sta[i-1];
}
N.sta[0]=temp;
temp=N.sta[7];
for(int i=7;i>4;i--)
{
N.sta[i]=N.sta[i-1];
}
N.sta[4]=temp;
}
void opC(node &N)
{
N.step++;
N.ans.push_back(‘C‘);
char temp=N.sta[1];
N.sta[1]=N.sta[5];
N.sta[5]=N.sta[6];
N.sta[6]=N.sta[2];
N.sta[2]=temp;
}
void BFS(string target)
{
queue<node> Q;
node now;
now.sta="12348765";
now.step=0;now.ans="";
vis[now.sta]=true;
Q.push(now);
while(!Q.empty())
{
node next;
node &N=next;
now=Q.front();
Q.pop();
if(now.sta==target)
{
cout<<now.step<<endl<<now.ans<<endl;
return;
}
next=now;
opA(N);
if(!vis[next.sta])
{
Q.push(next);
vis[next.sta]=true;
}
next=now;
opB(N);
if(!vis[next.sta])
{
Q.push(next);
vis[next.sta]=true;
}
next=now;
opC(N);
if(!vis[next.sta])
{
Q.push(next);
vis[next.sta]=true;
}
}
}
int main()
{
freopen("msquare.in","r",stdin);
freopen("msquare.out","w",stdout);
string target;
char ch;
for(int i=0;i<8;i++)
{
scanf("%c",&ch);
target.push_back(ch);
getchar();
}
swap(target[5],target[6]);//题目是按顺时钟的,而我按从上到下,从左到右处理的
swap(target[7],target[4]);
BFS(target);
return 0;
}
原文:http://www.cnblogs.com/modengdubai/p/4824198.html