zoj 1091 Knight Moves

/*中午又熬了,做出来了,还值得小高兴一下,呵呵
我的第一道宽度优先搜索
注意横纵坐标及从'a''1'开始的吧
感觉是个好题
不过不会c++很吃力啊可怜*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int dir[8][2] = {{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}};
int flag[8][8];
struct node
{
    int x,y,step;
}q[10000]; 
struct node N,P;
int main()
{
    char a,b,c,d;
   
    int front,rear,i;
    
    while(scanf(" %c%c %c%c",&a,&b,&c,&d)!=EOF)
    { 
        memset(flag,0,sizeof(flag));
        int c1 = a - 'a';
        int r1 = b - '1';
        int c2 = c - 'a';
        int r2 = d - '1';
        N.x = r1;
        N.y = c1;
        N.step = 0;
        flag[r1][c1] = 1;
        q[0] = N;
        front = 0;
        rear = 1;
        while(front < rear)
        {
            N = q[front++];
            if(N.x == r2  &&  N.y == c2)
                break;
            for(i=0;i<8;i++)
            {
                 int tx = N.x + dir[i][0];
                 int ty = N.y + dir[i][1];
                 if(tx>=0&&tx<8 && ty>=0&&ty<8 && flag[tx][ty]!=1)
                 {
                        P.x = tx;
                        P.y = ty;
                        P.step = N.step + 1;
                        q[rear++] = P;
                        flag[tx][ty] = 1;
                 }
            }
        }
        printf("To get from %c%c to %c%c takes %d knight moves.\n",a,b,c,d,N.step);

    }
    return 0;
}


 

posted on 2011-08-21 14:57  java课程设计例子  阅读(135)  评论(0编辑  收藏  举报