B - Knight Moves UVA - 439

2 篇文章 0 订阅

#include <cstdio>
#include <cmath>
using namespace std;
typedef long long ll;
//走的是日字,以为任意两点间走六步即可到达,所以只要超过六步就停止,深度优先搜索会产生很多分支,所以一定要设置边界否则一定超时
int num[9][9];
int comun[8][2]= {{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1}};
int s_x,s_y,e_x,e_y;
int minn=0x7f7f7f7f;
void work(int x,int y,int sizen)
{
   if(sizen>6)
    return;
    if(x==e_x&&y==e_y)
    {
        if(minn>sizen)
        minn=sizen;
        return;
    }
    for(int i=0; i<8; i++)
    {
        int xx=x+comun[i][0];
        int yy=y+comun[i][1];
        if(xx>0&&xx<9&&yy>0&&yy<9&&num[xx][yy])
        {
            num[xx][yy]=0;
            work(xx,yy,sizen+1);
            num[xx][yy]=1;
        }
    }
}
int main()
{
    char c,c1;
    int a,b;
    for(int i=1;i<=8;i++)
        for(int j=1;j<=8;j++)
        num[i][j]=1;
    while(~scanf("%c%d %c%d",&c,&a,&c1,&b))
    {
        // printf("To get from %c%d to %c%d takes ",c,a,c1,b);

       // for(int i=0; i<9; i++)
            //printf("%d %d \n",comun[i][0],comun[i][1]);
           int  sizen=0;
       minn=0x7f7f7f7f;
        s_x=a;
        s_y=c-'a'+1;
        e_x=b;
        e_y=c1-'a'+1;
        num[s_x][s_y]=0;
        printf("To get from %c%d to %c%d takes ",c,a,c1,b);
        work(s_x,s_y,sizen);
        printf("%d knight moves.\n",minn);
        num[s_x][s_y]=1;
        getchar();

    }
    return 0;
}
宽度优先搜索

 

#include <cstdio>
#include <cmath>
#include <queue>
using namespace std;
//走的是日字
int comun[8][2]= {{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1}};
int s_x,s_y,e_x,e_y;
const int INF=0x3f3f3f3f;
typedef pair<int,int>P;
int num[9][9];

int bfs()
{queue<P>que;
    que.push(P(s_x,s_y));//放在外面一定注意clear
    while(que.size())
    {
        P p=que.front();
        que.pop();
        if(p.first==e_x&&p.second==e_y)
            break;
        for(int i=0; i<8; i++)
        {
            int xx=p.first+comun[i][0];
            int yy=p.second+comun[i][1];
            if(xx>0&&xx<9&&yy>0&&yy<9&&num[xx][yy]==INF)
            {
                que.push(P(xx,yy));
                num[xx][yy]=num[p.first][p.second]+1;
            }
        }
    }
    return num[e_x][e_y];
}
int main()
{
    char c,c1;
    int a,b;
    while(~scanf("%c%d %c%d",&c,&a,&c1,&b))
    {
        for(int i=1; i<=8; i++)
            for(int j=1; j<=8; j++)
                num[i][j]= INF;
        s_x=a;
        s_y=c-'a'+1;
        e_x=b;
        e_y=c1-'a'+1;
        num[s_x][s_y]=0;
        printf("To get from %c%d to %c%d takes ",c,a,c1,b);
        printf("%d knight moves.\n",bfs());
        getchar();
    }
    return 0;
}
 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值