UVA439 Knight Moves(BFS)

本题vjudge链接

  • 题意:在象棋里,给马的起点和终点,计算最小移动步数
#include <bits/stdc++.h>
#define mk(a, b) make_pair(a, b)
using namespace std;
using pii = pair<int, int>;
using pdi = pair<pii, int>;

int sx, sy, ex, ey;
bool vis[10][10];
char a[5], b[5];
const int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2};
const int dy[] = {-1, -2, -2, -1, 1, 2, 2, 1};

inline bool cherk(int x, int y) { return x > 0 && y > 0 && x < 9 && y < 9; }

void print(int num) {
    printf("To get from %s to %s takes %d knight moves.\n", a, b, num);
}

void bfs() {
    queue<pdi> q;
    q.push(mk(mk(sx, sy), 0));
    vis[sx][sy] = true;
    while (q.size()) {
        int x = q.front().first.first, y = q.front().first.second;
        int num = q.front().second;
        q.pop();
        if (x == ex && y == ey) { print(num); return;}
        for (int i = 0; i < 8; i++) {
            int l = x + dx[i], r = y + dy[i];
            if (cherk(l, r) && !vis[l][r]) {
                q.push(mk(mk(l, r), num + 1));
                vis[x][y] = true;
            }
        }
    }
}

int main () {
#ifndef ONLINE_JUDGE
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif
    while (~scanf("%s %s", a, b)) {
        sx = a[0] - 'a' + 1, sy = a[1] - '0';
        ex = b[0] - 'a' + 1, ey = b[1] - '0';
        bfs();
        memset(vis, 0, sizeof vis);
    }

    return 0;
}

原地址

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值