《算法竞赛从入门到进阶》心得及相关题解020--bfs--hdu1372


题目意思:hdu1372,问国际象棋中的马从起始位置到目标位置至少要几步。
解题思路:水题,bfs,连坑都没有。

代码明细:

//probID: hdu1372
//author: WiselyQY
//date: 2021-01-04
#include <bits/stdc++.h>
using namespace std;

struct Node
{
    int x,y,step;
};
const int INF=1<<30;
int sx,sy,ex,ey,vis[10][10],ans;
char scx,scy,ecx,ecy,g[10][10];
queue<Node> q;
const int dx[]={2,1,-1,-2,-2,-1,1,2}, dy[]={1,2,2,1,-1,-2,-2,-1};
int in(int x, int y)
{
    return x>=1 && x<=8 && y>=1 && y<=8;
}
void bfs()
{
    while(!q.empty()) q.pop();
    memset(vis,0,sizeof(vis));
    vis[sx][sy]=1;
    Node u;
    u.x=sx; u.y=sy; u.step=0;
    q.push(u);
    while(!q.empty())
    {
        u=q.front(); q.pop();
        int x=u.x, y=u.y, step=u.step;
        if(x==ex && y==ey) {ans=step; return;}
        for(int i=0; i<8; i++)
        {
            int nx=x+dx[i], ny=y+dy[i];
            if(in(nx,ny) && !vis[nx][ny])
            {
                vis[nx][ny]=1;
                Node nu;
                nu.x=nx; nu.y=ny; nu.step=step+1;
                q.push(nu);
            }
        }
    }
}
int main()
{
    clock_t start,end;
    start=clock();
#ifndef ONLINE_JUDGE
    freopen(R"(D:\code\hdu\1372\in.txt)","r",stdin);
#endif
    while(cin>>scx>>scy>>ecx>>ecy)
    {
        sx=scx-'a'+1; sy=scy-'0';
        ex=ecx-'a'+1; ey=ecy-'0';
        ans=INF;
        bfs();
        cout<<"To get from "<<scx<<scy<<" to "<<ecx<<ecy<<" takes "<<ans<<" knight moves."<<endl;
    }
    end=clock();
    //printf("time=%lfs\n",(double)(end-start)/1000);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值