ACM小组的Samsara和Staginner对中国象棋特别感兴趣,尤其对马(可能是因为这个棋子的走法比较多吧)的使用进行深入研究。今天他们又在 构思一个古怪的棋局:假如Samsara只有一个马了,而Staginner又只剩下一个将,两个棋子都在棋盘的一边,马不能出这一半棋盘的范围,另外这 一半棋盘的大小很奇特(n行m列)。Samsara想知道他的马最少需要跳几次才能吃掉Staginner的将(我们假定其不会移动)。当然这个光荣的任 务就落在了会编程的你的身上了。
Input
每组数据一行,分别为六个用空格分隔开的正整数n,m,x1,y1,x2,y2分别代表棋盘的大小n,m,以及将的坐标和马的坐标。(1<=x1,x2<=n<=20,1<=y1,y2<=m<=20,将和马的坐标不相同)
Output
输出对应也有若干行,请输出最少的移动步数,如果不能吃掉将则输出“-1”(不包括引号)。
Sample Input
8 8 5 1 4 5
Sample Output
3
Hint
搜索模板题
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>
typedef long long LL;
typedef long double LD;
using namespace std;
const int maxn=22;
char ma[maxn][maxn];
int vis[maxn][maxn];
//int f[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
//int f[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int f[8][2]={{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{1,-2},{-1,2},{1,2}};
int N,M,T;
struct node
{
int x,y;
int step;
friend bool operator <(node a,node b)
{
return a.step>b.step;
}
};
priority_queue<node>q;
bool OK(int x,int y)
{
if(x>0&&y>0&&x<=N&&y<=M)
return true;
return false;
}
void bfs(node st,node en)
{
q.push(st);
vis[st.x][st.y]=0;
while(!q.empty())
{
node t=q.top();
q.pop();
//printf("*****%d %d %d\n",t.x,t.y,t.step);
if(t.x==en.x&&t.y==en.y)
{
printf("%d\n",t.step);
return;
}
for(int i=0;i<8;i++)
{
int xx=t.x+f[i][0];
int yy=t.y+f[i][1];
if(OK(xx,yy)&&(vis[xx][yy]>t.step+1||vis[xx][yy]==-1))
{
// printf("%d %d %d\n",xx,yy,t.step+1);
q.push((node){xx,yy,t.step+1});
vis[xx][yy]=t.step+1;
}
}
}
printf("-1\n");
}
int main()
{
node st,en;
while(~scanf("%d%d%d%d%d%d",&N,&M,&en.x,&en.y,&st.x,&st.y))
{
memset(vis,-1,sizeof(vis));
while(!q.empty())q.pop();
st.step=0;
bfs(st,en);
}
return 0;
}