ZOJ 1091.Knight Moves

国际象棋的马移动,分别向八个方向作广度优先搜索,找到最小步数。

BFS()简单应用。

#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct Point{
    //点
    int x;
    int y;
};
struct QP{
    //从开始到这点所需步数
    Point p;
    int move;
};
bool operator==(const Point &a,const Point &b){
    //重载==
    if(a.x == b.x && a.y == b.y)return true;
    return false;
}
int way[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,-1},{2,1},{-1,-2},{1,-2}};
int steps(Point begin, Point end){
    //计算最短步数
    bool visited[8 + 1][8 + 1] = {0,0};
    queue<QP> q;
    QP current;
    current.p = begin;
    current.move = 0;
    visited[current.p.x][current.p.y] = 1;
    q.push(current);
    while(!q.empty()){
        current = q.front();
        q.pop();
        if(current.p == end)break;
        for(int i=0; i<8; i++){
            if(current.p.x + way[i][0] <= 8 && current.p.x + way[i][0] >= 1 && current.p.y + way[i][1] <= 8 && current.p.y + way[i][1] >= 1 && !visited[current.p.x + way[i][0]][current.p.y + way[i][1]]){
                visited[current.p.x + way[i][0]][current.p.y + way[i][1]] = 1;
                QP temp;
                temp.p.x = current.p.x + way[i][0];
                temp.p.y = current.p.y + way[i][1];
                temp.move = current.move + 1;
                q.push(temp);
            }
        }
    }
    return current.move;
}
int main(){
    string s1,s2;
    Point begin,end;
    while(cin>>s1>>s2){
        begin.y = s1[0] - 'a' + 1;
        begin.x = s1[1] - '0';
        end.y = s2[0] - 'a' + 1;
        end.x = s2[1] - '0';
        cout<<"To get from "<<s1<<" to "<<s2<<" takes "<<steps(begin,end)<<" knight moves."<<endl;
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值