
4 4 4 5 5 4 6 5 2 4 3 3 3 6 4 6
YES
题意就是有四颗棋子,能否在8步内走到目标状态
开个8维数组记录状态即可
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
bool vis[8][8][8][8][8][8][8][8];
bool map[10][10];
int to[4][2] = {1,0,-1,0,0,1,0,-1};
struct point
{
int x[4],y[4],step;
} s,e;
int check(point a)//判断是否为最终态
{
for(int i = 0; i<4; i++)
{
if(!map[a.x[i]][a.y[i]])
return 0;
}
return 1;
}
int empty(point a,int k)//看要将要到达的那格是否为空
{
for(int i = 0; i<4; i++)
{
if(i!=k && a.x[i] == a.x[k] && a.y[i] == a.y[k])
return 0;
}
return 1;
}
int judge(point next)//判断是否符合要求
{
int i;
for(i = 0; i<4; i++)
{
if(next.x[i]<0 || next.x[i]>=8 || next.y[i]<0 || next.y[i]>=8)
return 1;
}
if(vis[next.x[0]][next.y[0]][next.x[1]][next.y[1]][next.x[2]][next.y[2]][next.x[3]][next.y[3]])
return 1;
return 0;
}
int bfs()
{
memset(vis,false,sizeof(vis));
int i,j;
queue<point> Q;
point a,next;
a.step = 0;
for(i = 0; i<4; i++)
{
a.x[i] = s.x[i];
a.y[i] = s.y[i];
}
Q.push(a);
vis[a.x[0]][a.y[0]][a.x[1]][a.y[1]][a.x[2]][a.y[2]][a.x[3]][a.y[3]] = true;
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(a.step>=8)//因为后面循环有判断减枝,所以这里要包括8步
return 0;
if(check(a))
return 1;
for(i = 0; i<4; i++)
{
for(j = 0; j<4; j++)
{
next = a;
next.x[i]+=to[j][0];
next.y[i]+=to[j][1];
next.step++;
if(judge(next))
continue;
if(empty(next,i))//要去的那一格是空
{
if(check(next))
return 1;
vis[next.x[0]][next.y[0]][next.x[1]][next.y[1]][next.x[2]][next.y[2]][next.x[3]][next.y[3]] = true;
Q.push(next);
}
else//非空则继续往前
{
next.x[i]+=to[j][0];
next.y[i]+=to[j][1];
if(judge(next) || !empty(next,i))//继续往前也要满足要求且是空格
continue;
if(check(next))
return 1;
vis[next.x[0]][next.y[0]][next.x[1]][next.y[1]][next.x[2]][next.y[2]][next.x[3]][next.y[3]] = true;
Q.push(next);
}
}
}
}
return 0;
}
int main()
{
int i;
while(~scanf("%d%d",&s.x[0],&s.y[0]))
{
s.x[0]--;
s.y[0]--;
for(i = 1; i<4; i++)
{
scanf("%d%d",&s.x[i],&s.y[i]);
s.x[i]--;
s.y[i]--;
}
memset(map,false,sizeof(map));
for(i = 0; i<4; i++)
{
scanf("%d%d",&e.x[i],&e.y[i]);
e.x[i]--;
e.y[i]--;
map[e.x[i]][e.y[i]] = true;
}
int flag = bfs();
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
HDU1401:Solitaire(BFS),布布扣,bubuko.com
原文:http://blog.csdn.net/libin56842/article/details/22829905