您的位置:首页 > 其它

POJ1915 - Knight Moves - 广度优先搜索

2014-07-16 09:11 267 查看
#include<stdio.h>
#include<string.h>
int n;
int mark[305][305];
int to[8][2]={{1,2},{-1,2},{1,-2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
struct
{
int x,y,id;
}st,ed,queue[100000],now,next;
int bfs()
{
memset(mark,0,sizeof(mark));
int fro,end;
fro=end=0;
st.id=0;
queue[end++]=st;
mark[st.x][st.y]=1;
while(fro<end)
{
now=queue[fro++];
if(now.x==ed.x&&now.y==ed.y)
{
return now.id;
}
for(int i=0;i<8;i++)
{
next.x=now.x+to[i][0];
next.y=now.y+to[i][1];
if(next.x<0||next.x>=n||next.y<0||next.y>=n||mark[next.x][next.y]==1)
{
continue;
}
next.id=now.id+1;
mark[next.x][next.y]=1;
queue[end++]=next;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
scanf("%d%d",&st.x,&st.y);
scanf("%d%d",&ed.x,&ed.y);
printf("%d\n",bfs());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: