1、简单描述
骑士在n*n的棋盘上按照图中的走法,从一点到另一点,最少走多少步?
2、思路
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
bool vis[400][400];
int a[400][400];
int n,sx,sy,ex,ey;
int dir[8][2]={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};
struct node
{
int x,y,step;
};
bool island(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<n)
return true;
else
return false;
}
int bfs()
{
queue<node>q;
node start,now,next;
start.x=sx;
start.y=sy;
start.step=0;
q.push(start);
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x == ex && now.y == ey)
return now.step;
for(int i = 0; i<8; i++)
{
next.x = now.x+dir[i][0];
next.y = now.y+dir[i][1];
if(next.x == ex && next.y == ey)
return now.step+1;
if (island(next.x,next.y)&&!vis[next.x][next.y])
{
next.step=now.step+1;
vis[next.x][next.y]=true;
q.push(next);
}
}
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n;
cin>>sx>>sy;
cin>>ex>>ey;
memset(vis,false,sizeof(vis));
vis[sx][sy]=true;
cout<<bfs()<<endl;
}
return 0;
}
广度优先搜索。