hdu1372-Knight Moves BFS

1372

求从他给的坐标走到另一个坐标需要多少步数,字母数字代表行列

走的规则就像马走日一样(可以先横走一步再竖两步,或者竖两步横一步一共有八个方向)


#include <iostream>    
#include <vector>
#include <queue>
#include <string>
using namespace std;    
char  map[9][9];
int judge[9][9];
int s1,s2,e1,e2;
string a,b;
int rule[8][2] = {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
struct node
{
    int step;
    int fx,fy;
};
int bfs()
{
    queue<node> que;
    node pre,next;
    pre.fx = s1;
    pre.fy = s2;
    pre.step = 0;
    que.push(pre);                   //先把第一次压入队列
    memset(judge,0,sizeof(judge));     //清空标记的数组
    judge[s1][s2] = 1;               //第一次标记
    while (!que.empty())
    {
        pre = que.front();           //取出队列中的第一个
        que.pop();                  //删除
        if(pre.fx == e1 && pre.fy ==e2)
            return pre.step;
        for (int i = 0; i < 8; i++)
        {       //符合条件
            if (pre.fx+rule[i][0]<9 && pre.fx+rule[i][0]>0 && 
                pre.fy+rule[i][1]<9 && pre.fy+rule[i][1]>0 && 
                judge[pre.fx+rule[i][0]][pre.fy+rule[i][1]] == 0)
            {    //【保持pre不动 动的只有next节点,再将next压入队列】
                next.fx= pre.fx+rule[i][0];
                next.step=pre.step+1;
                next.fy = pre.fy+rule[i][1];
                judge[next.fx][next.fy] = 1; //标记,不走回头路
                que.push(next); 
            }
        }
    }
    return 0;
}
int main()
{

    while (cin>>a>>b)
    {
        s1 = a[0]-'a'+1;
        s2 = a[1]-'0';
        e1 = b[0]-'a'+1;
        e2 = b[1]-'0';
        cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs()<<" knight moves."<<endl;
    }    
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值