Problem: 搜索二·骑士问题
Description: 国际象棋棋盘中有三个马,问这三个马最少走几步能走到同一个格子。一次只能走一个棋子。
Solution: 基础的广搜题目,用一个6维数组保存当前状态。
Code(C++):
#include <stdio.h>
#include <string.h>
typedef struct tagPoint{
int x,y;
tagPoint(){}
tagPoint(int x,int y)
{
this->x=x;
this->y=y;
}
bool operator==(tagPoint &o)
{
return this->x==o.x&&this->y==o.y;
}
}Point;
typedef struct tagNode{
Point a[3];
int step;
tagNode(){}
tagNode(Point a[],int step)
{
for(int i=0;i<3;i++)
this->a[i]=a[i];
this->step=step;
}
bool operator==(tagNode &o)
{
return a[0]==a[1]&&a[1]==a[2];
}
}Node;
const int QUEUE_TOP=10000000;
const int dirx[]={-2,2,1,-1,-2,2,1,-1,};
const int diry[]={1,1,2,2,-1,-1,-2,-2,};
Point points[3];
Node que[QUEUE_TOP];
int head,tail;
bool used[9][9][9][9][9][9];
int bfs()
{
if(points[0]==points[1]&&
points[1]==points[2]){
return 0;
}
head=tail=0;
memset(used,false,sizeof(used));
que[tail++]=Node(points,0);
used[points[0].x][points[0].y][points[1].x][points[1].y][points[2].x][points[2].y]=true;
while(tail!=head){
Node pre=que[head++];
head%=QUEUE_TOP;
for(int i=0;i<3;i++)
for(int j=0;j<8;j++){
Point now_point=Point(pre.a[i].x+dirx[j],
pre.a[i].y+diry[j]);
Node now=pre;
++now.step;
now.a[i]=now_point;
if(!(now_point.x>=1&&now_point.x<=8&&now_point.y>=1&&now_point.y<=8))
continue;
if(now.a[0]==now.a[1]&&now.a[1]==now.a[2])
return now.step;
if(!used[now.a[0].x][now.a[0].y][now.a[1].x][now.a[1].y][now.a[2].x][now.a[2].y]){
used[now.a[0].x][now.a[0].y][now.a[1].x][now.a[1].y][now.a[2].x][now.a[2].y]=true;
que[tail++]=now;
tail%=QUEUE_TOP;
}
}
}
return 0;
}
int main()
{
int N;
for(scanf("%d",&N);N--;){
char a[3][3];
for(int i=0;i<3;i++){
scanf("%s",a[i]);
points[i]=Point(a[i][0]-'A'+1,a[i][1]-'0');
}
int ans=bfs();
printf("%d\n",ans);
}
return 0;
}