UVA 439-Knight Moves

UVA 439-Knight Moves

题目大意:给出国际象棋棋盘俩个坐标,求马从坐标1到坐标2的最短步数

解题思路:bfs寻找最短路

#include <stdio.h>
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
struct kni{
    int x, y, d;
};
int dir[8][2] = {{1, 2}, {-1, 2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, -2}, {-1, -2}};
queue<kni> que;
int map[9][9];
int bfs(int a, int b) {
    while(!que.empty()) {
        if(que.front().x == a && que.front().y == b)
            return 0;
        for(int i = 0; i < 8; i++) {
            int c = que.front().x + dir[i][0], d = que.front().y + dir[i][1];
            if(c > 0 && c <= 8 && d > 0 && d <= 8 && map[c][d] == 0) {
                if(c == a && d == b)
                    return que.front().d + 1;
                else {
                    map[que.front().x][que.front().y] = 1;
                    kni kk;
                    kk.x = c;
                    kk.y = d;
                    kk.d = que.front().d+1;
                    que.push(kk);
                }
            }
        }
        que.pop();
    }
    return -1;
}
int main() {
    char ch1, ch2;
    int x1, x2, y1, y2;
    while(cin >> ch1 >> y1 >> ch2 >> y2) {
        while(!que.empty())
            que.pop();
        memset(map, 0, sizeof(map));
        x1 = ch1 - 'a' + 1;
        x2 = ch2 - 'a' + 1;
        kni k;
        k.x = x1;
        k.y = y1;
        k.d = 0;
        que.push(k);
        int re = bfs(x2, y2);
        printf("To get from %c%d to %c%d takes %d knight moves.\n", ch1, y1, ch2, y2, re);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值