UVa 439 - Knight Moves

第一个BFS,费了点时间~~

题目本身就是象棋里马走“日”,每次共8种走法,记录走过的格子,有限次数内能搜到目标格 ~~

代码如下:

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<string>
using namespace std;
int a[10][10],flag[10][10],count;
int step[10][3]= {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{-2,1},{2,-1},{-2,-1}};   // 8种走法~
int BFS(int x1,int y1,int x2,int y2)
{
    int tail=1,head=0,list[100][3],ct[100];
    list[head][0]=x1;
    list[head][1]=y1;
    flag[x1][y1]=1;
    ct[head]=0;
    while(head<tail)
    {
        for(int i=0; i<8; i++)
        {
            int fx=step[i][0]+list[head][0],fy=step[i][1]+list[head][1];
            if(fx>0&&fx<=8 && fy>0&&fy<=8 && !flag[fx][fy])
            {
                if(fx==x2&&fy==y2) return count=ct[head]+1;
                list[tail][0]=fx;
                list[tail][1]=fy;
                ct[tail++]=ct[head]+1;       //相当于每往外搜一圈,步数就要加一
                flag[fx][fy]=1;
            }
        }
        head++;
    }
    return 0;
}
int main()
{
#ifdef test
    freopen("sample.txt","r",stdin);
#endif
    int m,n;
    char km,kn;
    while(scanf("%c%d %c%d",&km,&m,&kn,&n)!=EOF)
    {
        getchar();
        memset(a,0,sizeof(a));
        memset(flag,0,sizeof(flag));
        int x1=km-'a'+1,y1=m,x2=kn-'a'+1,y2=n;
        count=0;
        count=BFS(x1,y1,x2,y2);
        printf("To get from %c%d to %c%d takes %d knight moves.\n",km,m,kn,n,count);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值