zoj 1091 BFS简单搜索

/*
题意:knight从一个位置移动到另一位置,求最少移动多少步

题解:BFS
*/
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

int dir[8][2] = {{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};//八个方向

bool m[10][10];

struct point
{
    int x,y;
    int deep;
};

int bfs(int sx, int sy, int ex, int ey)
{
    if (sx == ex && sy == ey)
        return 0;
    struct point start,end;
    start.x = sx;
    start.y = sy;
    start.deep = 0;
    end.x = ex;
    end.y = ey;
    memset(m,false,sizeof(m));
    queue<struct point> Q;
    Q.push(start);
    int ret = 0;
    bool flag = false;
    while (!Q.empty())
    {
        struct point tmp,t = Q.front();
        Q.pop();
        m[t.x][t.y] = true;
        for(int i=0; i<8; i++)
        {
            int tx = t.x+dir[i][0];
            int ty = t.y+dir[i][1];
            if (1<=tx && tx<=8 && 1<=ty && ty<=8 && !m[tx][ty])
            {
                if (tx == ex && ty == ey)
                    return t.deep+1;
                tmp.x = tx;
                tmp.y = ty;
                tmp.deep = t.deep+1;
                Q.push(tmp);
                m[tx][ty] = true;
            }
        }
    }
    return ret;
}

int main(void)
{
    char s1[5],s2[5];
    while (scanf("%s%s",s1,s2) == 2)
    {
        printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs(s1[0]-'a'+1,s1[1]-'0',s2[0]-'a'+1,s2[1]-'0'));
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/toufu/p/3614927.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值