Knight Moves(BFS+DFS)

在这里插入图片描述
简单搜索问题,然后刚开始我用的DFS,超时,
后面改用BFS,才过的…
DFS代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a1[9][9]={0};
int a2[8][2]={{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,1},{-2,-1}};
int x1,x2,y1,y2;
int sum,ans;
void DFS(int x,int y,int ans)
{
    if(x==x2&&y==y2)         //找到目标
    {
        sum=ans;
        return;
    }
    if(ans>sum)         //剪枝
        return;
    else
    {
        for(int i=0;i<8;i++)
        {
            int X=x+a2[i][0];
            int Y=y+a2[i][1];
            if(X>0&&X<=8&&Y>0&&Y<=8&&a1[X][Y]!=1)
            {
                a1[X][Y]=1;
                DFS(X,Y,ans+1);
                a1[X][Y]=0;
            }
        }
    }
    return;
}
int main()
{
    char c[6];
    while(gets(c))
    {
        memset(a1,0,sizeof(a1));
        x1=c[0]-'a'+1;      //起点
        x2=c[3]-'a'+1;   //终点
        y1=c[1]-'0';      //起点
        y2=c[4]-'0';   //终点
        sum=999;
        ans=0;
        a1[x1][y1]=1;
        DFS(x1,y1,ans);
        printf("%d\n",sum);
    }
    return 0;
}

BFS代码:

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int a1[9][9]={0};
int a2[8][2]={{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,1},{-2,-1}};
int x1,x2,y1,y2;
int sum,ans;
queue < int > q1;
void BFS()
{
    while(!q1.empty())
    {
    int x=q1.front();
    q1.pop();
    int y=q1.front();
    q1.pop();
    ans=q1.front();
    q1.pop();
    if(x==x2&&y==y2)
    {
        sum=ans;
        return;
    }
    if(ans>sum)
        return;
        for(int i=0;i<8;i++)
        {
            int X=x+a2[i][0];
            int Y=y+a2[i][1];
            if(X>0&&X<=8&&Y>0&&Y<=8&&a1[X][Y]!=1)
            {
                q1.push(X);
                q1.push(Y);
                q1.push(ans+1);
                a1[X][Y]=1;
            }
        }
    }
    return;
}
int main()
{
    char c[6];
    while(gets(c))
    {
        memset(a1,0,sizeof(a1));
        while(!q1.empty())
            q1.pop();
        x1=c[0]-'a'+1;
        x2=c[3]-'a'+1;
        y1=c[1]-'0';
        y2=c[4]-'0';
        sum=999;
        ans=0;
        a1[x1][y1]=1;
        q1.push(x1);
        q1.push(y1);
        q1.push(ans);
        BFS();
        printf("To get from %c%c to %c%c takes %d knight moves.\n",c[0],c[1],c[3],c[4],sum);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值