UVA 439 BFS 骑士的移动

本文介绍了一个使用C++实现的寻找骑士在国际象棋盘上从一个位置到另一个位置所需的最少移动次数的算法。该算法采用广度优先搜索(BFS),并利用优先队列来高效地找到最短路径。
#include<iostream>
#include<cstdio>
#include<string>
#include<string.h>
#include<math.h>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
int dx,dy;
struct node{
    int step;
    int x;
    int y;
   friend  bool operator <(node a,node b){
        return a.step>b.step;
    }
};
int dir[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{2,-1},{1,-2}};
priority_queue<node> q;
int  bfs(){

    int s,d;
    while(!q.empty()){
        node temp=q.top();
        q.pop();
        if(dx==temp.x&&dy==temp.y){return temp.step;}
        for(int i=0;i<8;i++){
            s=temp.x+dir[i][0];
            d=temp.y+dir[i][1];
            if(s>0&&s<9&&d>0&&d<9){
                node next;
                next.x=s;
                next.y=d;
                next.step=temp.step+1;
                q.push(next);
            }
        }
    }
    return 0;
}
int main(){
  int a,b,ss;
  char f,g;
  while(cin>>f>>b>>g>>dy){
        a=f-'a'+1;
        dx=g-'a'+1;
        while(!q.empty()) q.pop();
    node n;
    n.x=a;
    n.y=b;
    n.step=0;
    q.push(n);
    ss=bfs();
    printf("To get from %c%d to %c%d takes %d knight moves.\n",f,b,g,dy,ss);
  }


  return 0;
  }

 

转载于:https://www.cnblogs.com/wintersong/p/5221510.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值