Background
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him canmove knights from one position to another so fast. Can you beat him?
The Problem
Your task is to write a program to calculate the minimum number of moves neededfor a knight to reach one point from another, so that you have the chance to befaster than Somurolov.
For people not familiar with chess, the possible knight moves are shown inFigure 1.
Input
The input begins with the number n of scenarios on asingle line by itself.
Next follow n scenarios. Each scenario consists of three lines containinginteger numbers. The first line specifies the length l of a side of the chessboard (4 <= l <= 300). The entire board has size l * l. The second andthird line contain pair of integers {0,
..., l-1}*{0, ..., l-1} specifying thestarting and ending position of the knight on the board. The integers areseparated by a single blank. You can assume that the positions are validpositions on the chess board of that scenario.
Output
For each scenario of the input you have to calculate theminimal amount of knight moves which are necessary to move from the startingpoint to the ending point. If starting point and ending point areequal,distance is zero. The distance must be
written on a single line.
Sample Input
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
Sample Output
5
28
0
题目分析:求象棋中,“马”从一个点跳到另一个点的最少步数。用bfs求最短路径。
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
bool vis[310][310];//标记数组
int n;
intdx[]={-1,-2,-2,-1,1,2,2,1},dy[]={2,1,-1,-2,-2,-1,1,2};//方向数组
struct P{//点类
int x,y;
};
struct Node{//队元素
Px;
int step;
};
int bfs(P a,P b){
memset(vis,false,sizeof(vis));
vis[a.x][a.y]=true;
Node now,next;
now.x=a;now.step=0;
queue<Node> q;//用队列实现bfs
q.push(now);
while(!q.empty()){
now=q.front();q.pop();
if(now.x.x==b.x && now.x.y==b.y){
return now.step;
}
for(int i=0;i<8;++i){
int xx=next.x.x=now.x.x+dx[i],yy=next.x.y=now.x.y+dy[i];
next.step=now.step+1;
if(xx>=0 && xx<n && yy>=0 && yy<n&& !vis[xx][yy]){
vis[xx][yy]=true;
q.push(next);
}
}
}
return 0;
}
int main()
{
int t;scanf("%d",&t);
while(t--){
scanf("%d",&n);
P a,b;
scanf("%d%d%d%d",&a.x,&a.y,&b.x,&b.y);
int ans=bfs(a,b);
printf("%d\n",ans);
}
return 0;
}