HDU 1372 Knight Moves (BFS)

题目链接

又是边界。。。错了两次,从今天开始准备期末考试,明显挑战很大啊!

#include <stdio.h>
#include <string.h>
int p[20][20],o1[300],o2[300];
int main()
{
    int i,j,k,start,end,c0,r0;
    int num;
    int change1[9]= {1,1,-1,-1,2,2,-2,-2};
    int change2[9]= {2,-2,2,-2,1,-1,1,-1};
    char c1,r1,c2,r2;
    while(scanf("%c%c%*c%c%c%*c",&c1,&r1,&c2,&r2)!=EOF)
    {
        memset(p,0,sizeof(p));
        num = 0;
        o1[0] = c1 - 'a' + 1;
        o2[0] = r1 - '0';
        c0 = c2 - 'a' + 1;
        r0 = r2 - '0';
        p[o1[0]][o2[0]] = 1;
        start = end = 0;
        for(;;)
        {
            j = 1;
            if(p[c0][r0])break;
            for(i = start; i <= end; i ++)
            {
                for(k = 0; k <= 7; k ++)
                {
                    if(o1[i]+change1[k]<=8&&o1[i]+change1[k]>=1&&o2[i]+change2[k]<=8&&o2[i]+change2[k]>=1)
                    {
                        if(p[o1[i]+change1[k]][o2[i]+change2[k]] == 0)
                        {
                            o1[end+j] = o1[i]+change1[k];
                            o2[end+j] = o2[i]+change2[k];
                            j ++;
                            p[o1[i]+change1[k]][o2[i]+change2[k]] = 1;
                        }
                    }
                }
            }
            start = end + 1;
            end = end + j - 1;
            num ++;
        }
        printf("To get from %c%c to %c%c takes %d knight moves.\n",c1,r1,c2,r2,num);
    }
    return 0;
}

  

 

posted @ 2012-06-04 22:03  Naix_x  阅读(132)  评论(0编辑  收藏  举报