HDU 2243 Knight Moves

来源:互联网 发布:励志类书籍推荐知乎 编辑:程序博客网 时间:2024/05/19 14:39

这是一道简单的BFS广搜的题目。看不懂画画图应该会有帮助。

#include <stdio.h>#include <string.h>int x1,x2,y1,y2,count;int z[9][9];int h[8][2]={{-1,-2},{-2,-1},{-2,1,},{-1,2},{1,2},{2,1},{1,-2},{2,-1}};char t1,t2;struct sa{    int x,y,step;}data[100];int bfs(int x,int y){    int r=0,l=0;    data[r].x=x;    data[r].y=y;    data[r++].step=0;    z[x][y]=1;    if (x==x2&&y==y2) return 0;    while (l<r)    {        sa now,next;        now.x=data[l].x;        now.y=data[l].y;        now.step=data[l++].step;        for (int a=0;a<8;a++)        {            next.x=now.x+h[a][0];            next.y=now.y+h[a][1];            next.step=now.step+1;            if (next.x>=1&&next.x<=8&&next.y>=1&&next.y<=8&&z[next.x][next.y]==0)            {                if (next.x==x2&&next.y==y2) return next.step;                z[next.x][next.y]=1;                data[r].x=next.x;                data[r].y=next.y;                data[r++].step=next.step;            }        }    }    return -1;}int main(){    while (scanf("%c%d %c%d",&t1,&y1,&t2,&y2)!=EOF)    {        x1=t1-'a'+1;        x2=t2-'a'+1;        //printf("%d %d %d %d",x1,x2,y2,y1);        memset(z,0,sizeof(z));        count=bfs(x1,y1);        printf("To get from %c%d to %c%d takes %d knight moves.\n",t1,y1,t2,y2,count);        count=0;        getchar();    }    return 0;}