您的位置:首页 > 其它

bfs-HDU 5012Dice

2016-10-14 12:28 267 查看
题意:

给出初状态,给出末状态,4个方向翻转最少几步。

思路:

一开始以为是个规律题。查了下是个搜索。知道是搜索就很好做了

#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;
struct node
{
int left,right,top,bottom,front,back,step;
};
node save[10000];
int cnt=0;
queue<node> s;
node ans;
bool Isover(node t1,node t2)
{
if(t1.front==t2.front&&t1.back==t2.back&&t1.bottom==t2.bottom&&t1.left==t2.left&&t1.right==t2.right&&t1.top==t2.top)
return true;
return false;
}
bool notemp(node t)
{
for(int i=1;i<=cnt;i++)
{
if(t.front==save[i].front&&t.back==save[i].back&&t.bottom==save[i].bottom&&t.left==save[i].left&&t.right==save[i].right&&t.top==save[i].top)
return false;
}
return true;
}
void solve(node temp,int x)
{
node f=temp;
if(x==1)
{
temp.left=f.top;
temp.right=f.bottom;
temp.top=f.right;
temp.bottom=f.left;
temp.front=f.front;
temp.back=f.back;
}
else if(x==2)
{
temp.left=f.bottom;
temp.right=f.top;
temp.front=f.front;
temp.back=f.back;
temp.top=f.left;
temp.bottom=f.right;
}
else if(x==3)
{
temp.left=f.left;
temp.right=f.right;
temp.front=f.top;
temp.back=f.bottom;
temp.top=f.back;
temp.bottom=f.front;
}
else if(x==4)
{
temp.left=f.left;
temp.right=f.right;
temp.front=f.bottom;
temp.back=f.top;
temp.top=f.front;
temp.bottom=f.back;
}
if(notemp(temp))
{
temp.step=f.step+1;
s.push(temp);
save[++cnt]=temp;
}
}
void bfs()
{
int yes=1;
while(!s.empty())
{

node t=s.front();
s.pop();
if(Isover(t,ans))
{
yes=0;
printf("%d\n",t.step);
break;
}
for(int i=1;i<=4;i++)
{
node temp=t;
solve(temp,i);
}

}
if(yes)
printf("-1\n");
return ;
}

int main()
{ node t;
while(scanf("%d%d%d%d%d%d",&t.top,&t.bottom,&t.left,&t.right,&t.front,&t.back)!=EOF)
{
cnt=0;
t.step=0;
scanf("%d%d%d%d%d%d"
4000
,&ans.top,&ans.bottom,&ans.left,&ans.right,&ans.front,&ans.back);
while(!s.empty())
s.pop();
s.push(t);
save[++cnt]=t;
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: