Description
Gregory is a grasshopper. His favourite food are clover leafs — he can simply never have enough
of them. Whenever he spots such a leaf, he wants to eat it as quickly as possible. Gregory is
also lazy, so he wants to move to the leaf with minimal effort. Your task is to help him to find
the shortest way to a clover leaf.
For simplicity, we will assume that Gregory lives on a rectangular grid consisting of unit squares.
As a grasshopper, he prefers to move by jumping (or, more exactly, hopping) from one square
to the other. Each hop takes him to a square that is in the adjacent row or column in one
direction, and two columns or rows away in the other direction. So, his hops resemble the moves
of a knight on a chessboard.
![](http://192.168.0.139/JudgeOnline/upload/201308/image/3/DDFLYAM5%7B9Y%60HZ_W6J%7BH~QJ.jpg)
Input
The input consists of several test cases, each of them specified by six integer numbers on one line:
R , C , GR, GC, L R,and L C, R and C specify the size of the grid in unit squares, 1 ≤ R, C ≤ 100.
Gregory cannot hop outside a rectangle of this size, because it would be too dangerous. Thevalues of GR ,G
C are the coordinates of the square that Gregory is standing on, and L R ,LC
are the coordinates of the square with the delicious clover leaf. (1 ≤ GR ,LR ≤ R ;1≤ GC ,LC ≤ C )
R , C , GR, GC, L R,and L C, R and C specify the size of the grid in unit squares, 1 ≤ R, C ≤ 100.
Gregory cannot hop outside a rectangle of this size, because it would be too dangerous. Thevalues of GR ,G
C are the coordinates of the square that Gregory is standing on, and L R ,LC
are the coordinates of the square with the delicious clover leaf. (1 ≤ GR ,LR ≤ R ;1≤ GC ,LC ≤ C )
Output
For each test case, print one integer number — the minimal number of hops that Gregory needs
to reach the square with his beloved delicacy. If it is not possible to reach that square at all,
print the word “impossible” instead.
Sample Input
10 10 10 10 1 1
2 2 1 1 1 2
8 8 1 1 1 2
Sample Output
6
impossible
3
分析:简单bfs,不需更新数据,但还是wa了好久,到后来居然是数组开小了!!!
代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
int n,m,x1,y1,x2,y2;
int dx[]={1,2,2,1,-1,-2,-2,-1};
int dy[]={2,1,-1,-2,-2,-1,1,2};
int que[100111],vis[100111],num[100111];//开始只开100010,差了那么一点,1000*100+100=100100
int dfs()
{
int front,rear,temp,next;
front=0,rear=1;
for(int j=0;j<=100111;j++)//这个怎么用memset()怎么不行!!!
{
vis[j]=0;
num[j]=0;
}
que[front]=x1*1000+y1;
vis[x1*1000+y1]=1;
while(rear>front)
{
temp=front++;
if(que[temp]==(1000*x2+y2))
return num[1000*x2+y2];
for(int i=0;i<8;i++)
{
int x=que[temp]/1000+dx[i];
int y=que[temp]%1000+dy[i];
if(x>0&&y>0&&x<=n&&y<=m&&!vis[1000*x+y])
{
vis[1000*x+y]=1;
que[rear++]=1000*x+y;
num[1000*x+y]=num[que[temp]]+1;
}
}
}
return 0;
}
int main()
{
while(scanf("%d%d%d%d%d%d",&n,&m,&x1,&y1,&x2,&y2)!=EOF)
{
if(x1==x2&&y1==y2)
printf("0\n");
else
{
int ans=dfs();
if(ans)
printf("%d\n",ans);
else
printf("%s\n","impossible");
}
}
return 0;
}