hdu 1372&&poj2243(BFS)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1072

一看到题目,感觉题目有点长,不怎么想读,匆匆读一遍,表示没怎么看懂,结果又仔细读了一遍,才知道规则就是“马走日”。

显然用bfs就AC了

#include<iostream>
#include<queue>
using namespace std;
bool vis[9][9];
int sx,sy,ex,ey;
char sta[3];
char End[3];
struct node
{
    int x,y;
    int step;
};
queue<node>q;
bool check(int x,int y)
{
    if(x<1||y<1||x>8||y>8)
        return false;
    return true;
}
void out(int n)
{
    printf("To get from %s to %s takes %d knight moves.\n",sta,End,n);
}
void bfs()
{
    int div[8][2]={{-1,-2},{-1,2},{-2,-1},{-2,1},{1,2},{1,-2},{2,1},{2,-1}};
    while(!q.empty())
        q.pop();
    node s;
    s.x=sx;
    s.y=sy;
    s.step=0;
    vis[sx][sy]=true;
    q.push(s);
    while(!q.empty())
    {
        s=q.front();
        q.pop();
        if(s.x==ex&&s.y==ey)
        {
            out(s.step);
            break;
        }
        node e;
        for(int i=0;i<8;i++)
        {
            e.step=s.step+1;
            e.x=s.x+div[i][0];
            e.y=s.y+div[i][1];
            if(check(e.x,e.y)&&vis[e.x][e.y]==false)
            {
                q.push(e);
                vis[s.x][s.y]=true;
            }
        }
    }
}
int main()
{
    //freopen("test.txt","r",stdin);
    while(scanf("%s%s",sta,End)!=EOF)
    {
        memset(vis,false,sizeof(vis));
        sx=sta[0]-'a'+1;
        sy=sta[1]-'0';
        ex=End[0]-'a'+1;
        ey=End[1]-'0';
        bfs();
    }
    return 0;
}

转载于:https://www.cnblogs.com/xiuyangleiasp/archive/2012/10/12/hdu1372.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值