您的位置:首页 > 其它

POJ_1915_KnightMoves

2015-07-25 08:55 351 查看
bfs

就是跟马的运动方式一样么……

#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;

const int M=305;

int isu[M][M];

int dx[8]={-2,-1,1,2,2,1,-1,-2};
int dy[8]={-1,-2,-2,-1,1,2,2,1};

queue<int>re;

int tot;

void bfs(int sx,int sy,int ex,int ey,int n)
{

while(!re.empty())
re.pop();
re.push(sx*n+sy);
isu[sx][sy]=1;
while(!re.empty())
{
int t=re.front();
re.pop();
int cx=t/n,cy=t%n;
//cout<<tot<<" "<<cx<<" "<<cy<<endl;
for(int i=0;i<8;i++)
{
int x=cx+dx[i],y=cy+dy[i];
if(0<=x&&x<n&&y>=0&&y<n&&!isu[x][y])
{
isu[x][y]=isu[cx][cy]+1;
re.push(x*n+y);
if(x==ex&&y==ey)
{
tot=isu[x][y];
return;
}
}
}
}
}

void clear()
{
for (int i = 0; i < M;i++)
for (int j = 0; j < M; j++)
isu[i][j] = 0;
}

int main()
{
int t;
int n,xj,yj,xm,ym;
scanf("%d",&t);
while (t--)
{
tot=0;
scanf("%d%d%d%d%d", &n,&xj,&yj,&xm,&ym);
if(xj==xm&&yj==ym)
{
printf("0\n");
continue;
}
clear();
bfs(xj,yj,xm,ym,n);
printf("%d\n", tot-1); //因为不算起点
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: