439 - Knight Moves (用的 bfs 做的,个人感觉bfs更适合这道题)

个人理解像这种在图里面寻找最短路线的问题,用bfs更靠谱。

宽度优先搜索,能够一层一层往下搜,更方便计数step。

dfs 则思路简单,代码难度小一些,在许多情况下更适合遍历。

方法就是比较普遍的方法,很好理解的。看过刘汝佳的书就能做出来。

#include<stdio.h>  
#include<string.h>  
#include<stdlib.h>  
using namespace std;  
int a1,a2,b1,b2;  
int ch1,ch2,ch;  
int q[20000];  
int dist[100][100];  
const int dx[]={1,2,-1,-2,1,2,-1,-2};  
const int dy[]={2,1,-2,-1,-2,-1,2,1};  
int bfs(int x,int y)  
{  
    if(x==a2&&y==b2)  
    {  
        dist[a2][b2]=0;  
        return 0;  
    }  
    int u;  
    int xx,yy;  
    int front=0;int rear=0;  
    u=8*x+y;  
    dist[x][y]=0;  
    q[rear++]=u;  
    while(front<rear)  
    {  
        u=q[front++];  
        x=u/8;y=u%8;  
        if(y%8==0)  
        {  
            y=8;  
            x=x-1;  
        }  
        for(int d=0;d<8;d++)  
        {  
            int newx=x+dx[d];  
            int newy=y+dy[d];  
            if(newx>=1&&newx<=8&&newy>=1&&newy<=8)  
            {  
                int v=newx*8+newy;  
                q[rear++]=v;  
                dist[newx][newy]=dist[x][y]+1;  
                if(newx==a2&&newy==b2)  
                    return 0;  
            }  
        }  
    }  
    return 0;  
}  
int main()  
{  
    char ch1,ch2,ch;  
    while(scanf("%c%d %c%d%c",&ch1,&a1,&ch2,&a2,&ch)!=EOF)  
    {  
        memset(dist,0,sizeof(dist));  
        b1=ch1-'a'+1;  
        b2=ch2-'a'+1;  
        bfs(a1,b1);  
        printf("To get from %c%d to %c%d takes %d knight moves.\n",ch1,a1,ch2,a2,dist[a2][b2]);  
    }  
    return 0;  
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值