HDU 1372 Knight Moves(BFS)

本文介绍了一种使用广度优先搜索(BFS)解决骑士在棋盘上行走问题的方法。通过定义骑士移动的八个方向,并利用队列进行节点扩展,可以有效地找到从起点到终点所需的最少步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

普通的BFS
注意一下马移动的八个方向就可以了

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
struct node{
    int x,y,steps;
    node(int x,int y,int steps):x(x),y(y),steps(steps) {}
    node() {}
};
int map[10][10];
int sx,sy,ex,ey;
char in1[5],in2[5];
int dx[8]={-1,-2,-2,-1,1,2,2,1};
int dy[8]={-2,-1,1,2,2,1,-1,-2};
int bfs(){
    memset(map,0,sizeof(map));
    queue<node> q;
    q.push(node(sx,sy,0));
    map[sx][sy]=1;
    while(!q.empty()){
        node first=q.front();
        q.pop();

        if(first.x==ex&&first.y==ey) return first.steps;

        for(int i=0;i<8;i++){
            node next;
            next.x=first.x+dx[i],next.y=first.y+dy[i];
            if(next.x>=0&&next.x<8&&next.y>=0&&next.y<8&&!map[next.x][next.y]){
                next.steps=first.steps+1;
                q.push(next);
                map[next.x][next.y]=1;
            }
        }

    }
}
int main(){
    while(~scanf("%s %s",in1,in2)){
        sx=in1[0]-'a',sy=in1[1]-'1';
        ex=in2[0]-'a',ey=in2[1]-'1';
        printf("To get from %s to %s takes %d knight moves.\n",in1,in2,bfs());

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值