牛客假日团队赛2 - F - 跳跃(最少步数)

本文深入探讨了骑士周游问题的解决方案,利用BFS(宽度优先搜索)算法在一个棋盘上寻找从起点到终点的最短路径。通过定义骑士的八个可能移动方向,实现了对棋盘的有效遍历,并通过队列数据结构实现节点的逐层搜索,最终找到从起点到终点的最短步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://ac.nowcoder.com/acm/contest/924/F

#include <bits/stdc++.h>
using namespace std;
#define debug(x) cerr<<#x<<'='<<(x)<<endl;
#define debugp(x) cerr<<#x<<"= {"<<(x.first)<<", "<<(x.second)<<"}"<<endl;
#define debug2(x, y) cerr<<"{"<<#x<<", "<<#y<<"} = {"<<(x)<<", "<<(y)<<"}"<<endl;
int n, m, M1, M2;
struct node
{
    int x, y, step;
}now, nex, st, ed;
int mp[50][50], vis[50][50], dir[8][2];
bool check()
{
    if(nex.x >= 0 && nex.x < n && nex.y >= 0 && nex.y < m && !vis[nex.x][nex.y] && mp[nex.x][nex.y] != 0 && mp[nex.x][nex.y] != 2)
        return true;
    return false;
}
void BFS()
{
    queue <node> q;
    q.push(st);
    vis[st.x][st.y] = 1;
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        for(int i = 0; i < 8; i++)
        {
            nex.x = now.x + dir[i][0];
            nex.y = now.y + dir[i][1];
            nex.step = now.step + 1;
            if(check())
            {
                if(nex.x == ed.x && nex.y == ed.y)
                {
                    cout << nex.step << endl;
                    return ;
                }
                vis[nex.x][nex.y] = 1;
                q.push(nex);
            }
        }
    }
    cout << "0" << endl;
}
int main()
{
    scanf("%d%d%d%d",&n, &m, &M1, &M2);
    dir[0][0] = M1, dir[0][1] = M2;
    dir[1][0] = M2, dir[1][1] = M1;
    dir[2][0] = M2, dir[2][1] = -M1;
    dir[3][0] = M1, dir[3][1] = -M2;
    dir[4][0] = -M1, dir[4][1] = -M2;
    dir[5][0] = -M2, dir[5][1] = -M1;
    dir[6][0] = -M2, dir[6][1] = M1;
    dir[7][0] = -M1, dir[7][1] = M2;
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            scanf("%d",&mp[i][j]);
            if(mp[i][j] == 3)
                st.x = i, st.y = j, st.step = 0;
            if(mp[i][j] == 4)
                ed.x = i, ed.y = j, ed.step = 0;
        }
    }
    BFS();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值