hdu 1372 Knight Moves

        hdu 1372 Knight Moves

        广搜, 那个Knight是走"日"字的, 就像中古想起里面的马走法一样哦, 那么它在不出范围的情况下就有8个方向哦.

         

#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;

struct cell {
    int x, y;
    int step;
};

int dir[8][2] = {-2, -1, -2, 1, -1, 2, 1, 2, 2, 1, 2, -1, 1, -2, -1, -2}; // 8个方向哦
bool visited[9][9];
cell start, end, go, to;

int bfs() {
    int i;
    queue<cell> Q;

    Q.push(start);
    memset(visited, false, sizeof(visited));
    visited[start.x][start.y] = true;

    while (!Q.empty()) {
        go = Q.front();
        Q.pop();

        for (i = 0; i < 8; i++) {
            to.x = go.x + dir[i][0];
            to.y = go.y + dir[i][1];
            to.step = go.step;

            if (to.x == end.x && to.y == end.y) {
                return to.step + 1;
            }

            if (to.x >= 1 && to.x <= 8 && to.y >= 1 && to.y <= 8 && !visited[to.x][to.y]) {
                ++to.step;
                visited[to.x][to.y] = true;
                Q.push(to);
            }
        }
    }

    return 0;
}

int main() {
    char s[3], e[3];
    int ans;

    while (scanf("%s %s", s, e) == 2) {
        start.x = s[1] - '0';
        start.y = s[0] - 'a' + 1;
        start.step = 0;

        end.x = e[1] - '0';
        end.y = e[0] - 'a' + 1;

        if (start.x == end.x && start.y == end.y) {
            printf("To get from %s to %s takes 0 knight moves.\n", s, e);
            continue ;
        }

        ans = bfs();
        printf("To get from %s to %s takes %d knight moves.\n", s, e, ans);
    }

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值