HDOJ 1372Knight Moves

马走日原题链接

题目描述:
在这里插入图片描述
思路:
BFS,借用二维数组使用for循环遍历八种情况,这样就不用一个一个写了

AC代码:

#include <iostream>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;

struct node
{
    int x, y;
    int steps;
}now,nex,target;

int m,n,step;
int vis[10][10];
int dir[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
char a1[10],a2[10];//记录目标点

void bfs()
{
    queue<node> qu;
    memset(vis,0,sizeof(vis));
    now.x = a1[0] - 'a' +1;
    now.y = a1[1] - '0';
    now.steps = 0;
    vis[now.x][now.y] = 1;
    qu.push(now);
    while(!qu.empty())
    {
        now = qu.front();
        qu.pop();
        if(now.x == m && now.y == n)
        {
            step = now.steps;
            return;
        }
        for(int i = 0; i < 8; i++)
        {
            nex.x = now.x + dir[i][0];
            nex.y = now.y + dir[i][1];

            if(nex.x >=1 && nex.x<= 8 && nex.y >= 1 && nex.y <=8 && !vis[nex.x][nex.y])
            {
                vis[nex.x][nex.y] = 1;
                nex.steps = now.steps + 1;
                qu.push(nex);
            }
        }
    }
}
int main()
{
    while(scanf("%s %s",&a1,&a2) != EOF)
    {
        m = a2[0] -'a' +1;
        n = a2[1] - '0';
        bfs();
        printf("To get from %s to %s takes %d knight moves.\n",a1, a2, step);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值