看他们都是找规律的,我竟然4个bfs暴力出来的,我就帖我的bfs代码吧。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#define N 9
#define check(a1,b1) ((a1)>0&&(a1)<9&&(b1)<9&&(b1>0))
using namespace std;
typedef struct {
int x,y;
int num;
}Node;
int di[8][2]={-1,-1,-1,0,-1,1,0,1,1,1,1,0,1,-1,0,-1};
int stra[4][2]={-1,0,0,1,1,0,0,-1};
int inc[4][2]={-1,-1,-1,1,1,1,1,-1};
int sx,sy,ex,ey;
int arr[4];
char str[10];
bool vis[9][9];
Node start,end;
int bfs0()
{
memset(vis,false,sizeof(vis));
queue<Node> q;
q.push(start);
Node now,next;
vis[sx][sy]=true;
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x==end.x&&now.y==end.y)
return now.num;
for(int i=0;i<8;++i)
{
int a = now.x+di[i][0];
int b = now.y+di[i][1];
if(check(a,b)&&!vis[a][b])
{
vis[a][b]=true;
next.x=a; next.y=b; next.num=now.num+1;
q.push(next);
}
}
}
return -1;
}
int bfs1()
{
memset(vis,false,sizeof(vis));
queue<Node> q;
vis[sx][sy]=true;
q.push(start);
Node now,next;
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x==end.x&&now.y==end.y)
return now.num;
for(int i=0;i<8;++i)
{
for(int j=1;j<=8;++j)
{
int a = now.x+j*di[i][0];
int b = now.y+j*di[i][1];
if(check(a,b)&&!vis[a][b])
{
vis[a][b]=true;
next.x=a; next.y=b; next.num=now.num+1;
q.push(next);
}
}
}
}
return -1;
}
int bfs2()
{
memset(vis,false,sizeof(vis));
queue<Node> q;
q.push(start);
Node now,next;
vis[sx][sy]=true;
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x==end.x&&now.y==end.y)
return now.num;
for(int i=0;i<4;++i)
{
for(int j=1;j<=8;++j)
{
int a = now.x+inc[i][0]*j;
int b = now.y+inc[i][1]*j;
if(check(a,b)&&!vis[a][b])
{
vis[a][b]=true;
next.x=a; next.y=b; next.num=now.num+1;
q.push(next);
}
}
}
}
return -1;
}
int bfs3()
{
memset(vis,false,sizeof(vis));
queue<Node> q;
q.push(start);
Node now,next;
vis[sx][sy]=true;
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x==end.x&&now.y==end.y)
return now.num;
for(int i=0;i<4;++i)
{
for(int j=1;j<=8;++j)
{
int a = now.x+stra[i][0]*j;
int b = now.y+stra[i][1]*j;
if(check(a,b)&&!vis[a][b])
{
vis[a][b]=true;
next.x=a; next.y=b; next.num=now.num+1;
q.push(next);
}
}
}
}
return -1;
}
int main(void)
{
int ncase;
cin>>ncase;
getchar();
while(ncase--)
{
gets(str);
sx=str[1]-'0';
sy=str[0]-'h'-1;
sy*=-1;
ex=str[4]-'0';
ey=str[3]-'h'-1;
ey*=-1;
start.x=sx; start.y=sy; start.num=0;
//cout<<sx<<" "<<sy<<" "<<ex<<" "<<ey<<endl;
end.x=ex; end.y=ey;
arr[0]=bfs0();
arr[1]=bfs1();
arr[2]=bfs2();
arr[3]=bfs3();
int tmp = arr[3];
arr[3]=arr[2];
arr[2]=tmp;
for(int i=0;i<4;++i)
if(i==0)
{
if(arr[i]==-1)
cout<<"Inf";
else
cout<<arr[i];
}
else
{
if(arr[i]==-1)
cout<<" Inf";
else
cout<<" "<<arr[i];
}
cout<<endl;
}
return 0;
}