poj 1915 Knight Moves

// 题意:图的大小L*L,可以向 8 个方向移动,求起点到终点的最短移动距离 
#include <iostream> // BFS
#include <string.h>

using namespace std;
const int MAXL=300;
int q[MAXL*MAXL],vis[MAXL][MAXL],dist[MAXL][MAXL];
const int dx[]={-1,-2,-2,-1,1,2,2,1};
const int dy[]={-2,-1,1,2,2,1,-1,-2};
int L,sx,sy,tx,ty;
void bfs()
{
vis[sx][sy]=1;
dist[sx][sy]=0;
q[0]=sx*L+sy;
int front=0,rear=1;
while(front<rear)
{
int z=q[front];
int x=z/L,y=z%L;
if(x==tx&&y==ty)
{
printf("%d\n",dist[tx][ty]);
break;
}
for(int d=0;d<8;++d)
{
int newx=x+dx[d];
int newy=y+dy[d];
int newz=newx*L+newy;
if(newx>=0&&newx<L&&newy>=0&&newy<L&& !vis[newx][newy] )
{
vis[newx][newy]=1;
q[rear]=newz;
dist[newx][newy]=dist[x][y]+1;
rear++;
}
}
front++;
}
}
int main()
{
int cases;
scanf("%d",&cases);
while(cases--)
{
scanf("%d%d%d%d%d",&L,&sx,&sy,&tx,&ty);
memset(vis,0,sizeof(vis));
bfs();
}
return 0;
}

posted on 2011-07-20 22:45  sysu_mjc  阅读(113)  评论(0编辑  收藏  举报

导航