knight moves

#include<iostream>
#include<queue>
#include<cstring>
#include<stdio.h>
using namespace std;
struct site { int l, r, ans; };
int vis[9][9]; 
int Move[8][2] = { {-1,2} ,{-1,-2},{1,2},{1,-2},{2,-1},{2,1},{-2,1},{-2,-1} };//move储存骑士的走法
bool in(int a, int b) {
    return a >= 1 && a <= 8 && b >= 1 && b <= 8;
}
int main() {
    char a, b; int r1, r2; site cur, next; int k;
    while (cin >> a >> r1 >> b >> r2) {
        bool judge = 0;
        int line1 = (int)a - 96; int line2 = (int)b - 96;//将字母列转化成数字;
        site start = { line1,r1,0 }, end = { line2,r2,0 };
        memset(vis, 0, sizeof(vis));
        queue<site>chess;
        chess.push(start);
        vis[start.l][start.r] = 1;
        while (!chess.empty()) {
            cur = chess.front();
            chess.pop();
            if (cur.l == end.l && cur.r == end.r) {
                judge = 1;
                k = cur.ans;
                break;
            }
            for (int i = 0; i < 8; i++) {
                next.l = cur.l + Move[i][0];
                next.r = cur.r + Move[i][1];
                if (in(next.l, next.r) && vis[next.l][next.r] == 0) {
                    next.ans = cur.ans + 1;
                    vis[next.l][next.r] = 1;
                    chess.push(next);
                }
            }//利用for循环减少代码量
        }
        
        cout << "To get from " << a << r1 << " to " << b << r2 << " takes " << k<< " knight moves." << endl;
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值