您的位置:首页 > 其它

uva 439 Knight Moves 骑士移动 —— bfs

2017-03-03 20:08 393 查看
代码如下:

#include<stdio.h>//bfs 骑士的移动
#include<string.h>
#include<stdlib.h>

struct
{
int x,y,z;
}q[1000];
int map[10][10],head = 0, tail = 0;
int d[8][2]={ {-1,-2}, {-1,2}, {1,-2}, {1,2}, {-2,-1}, {-2,1}, {2,-1}, {2,1} };

int bfs(int x,int y,int xo,int yo)
{
if(x==xo && y==yo)
return 0;

q[tail].x = x; q[tail].y = y; tail++; map[x][y] = 1;
while(tail!=head)
{
for(int i = 0;i<8;i++)
{
int xx = q[head].x + d[i][0];
int yy = q[head].y + d[i][1];
if(!map[xx][yy] && xx>0 && xx<9 && yy>0 && yy<9)
{
if(xx==xo && yy==yo)
return q[head].z+1;
map[xx][yy] = 1;
q[tail].x = xx; q[tail].y = yy; q[tail].z = q[head].z+1; tail++;
}
}
head++;
}
return -1;
}

int main()
{
int x,y,xo,yo,step;
memset(map,0,sizeof(map));
memset(q,0,sizeof(q));
scanf("%d %d %d %d",&x,&y,&xo,&yo);
step = bfs(x,y,xo,yo);
step>=0? printf("%d",step):printf("no way");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: