POJ 1915 Knight Moves

就是简单的BFS,刚开始还在想要不要剪枝,后来试了一下不用剪枝就能过,可能因为不是马周游吧,虽然棋盘可以很大,但递归层数不是那么深。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int MAXN = 305;
int vis[MAXN][MAXN], dist[MAXN][MAXN];

int dir[8][2] = {1, 2, 1, -2, -1, 2, -1, -2, 2, 1, 2, -1, -2, 1, -2, -1};
int kase = 0, X, Y;
int sx, sy, ex, ey;

struct Node
{
    int x, y;
    Node(int r, int c)
    {
        x = r, y = c;
    }
};

queue<Node> Q;

int BFS()
{
    while (!Q.empty())
        Q.pop();
    if (sx == ex && sy == ey)
        return 0;
    dist[sx][sy] = 0;
    vis[sx][sy] = kase;
    Q.push(Node(sx, sy));
    while (!Q.empty())
    {
        Node node = Q.front();
        Q.pop();
        int r = node.x, c = node.y;
        for (int i = 0; i < 8; i++)
        {
            int nx = r + dir[i][0];
            int ny = c + dir[i][1];
            if (nx >= 0 && nx < X && ny >= 0 && ny < Y && vis[nx][ny] != kase)
            {
                if (nx == ex && ny == ey)
                    return dist[r][c] + 1;
                dist[nx][ny] = dist[r][c] + 1;
                vis[nx][ny] = kase;
                Q.push(Node(nx, ny));
            }
        }
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        kase++;
        scanf("%d", &X);
        Y = X;
        scanf("%d%d", &sx, &sy);
        scanf("%d%d", &ex, &ey);
        printf("%d\n", BFS());
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值