骑士游历

本文介绍了一个经典的宽度优先搜索(BFS)算法应用案例:计算骑士从棋盘左上角到达右下角所需的最少移动步数。通过使用队列来存储当前位置及其对应的移动步数,并结合方向偏移量数组实现对合法移动路径的探索。

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

问题描述

这里写图片描述

输入

输入n和m

输出

输出最少的步数

样例输入

6 5

样例输出

3

题目解读

这道题可谓是BFS的经典习题。
我们设计两个队列Q,step,分别用来储存当前的状态、当前状态所对应的步数
每次读取状态的时候分别取两个队列的队首,伸展向四个日字格即可

code

#include <bits/stdc++.h>

using namespace std;

inline int read() {
    int x = 0 , f = 1; char ch = getchar();
    for ( ; !isdigit(ch) ; ch = getchar()) if (ch == '-') f = -1;
    for ( ; isdigit(ch) ; ch = getchar()) x = x * 10 + ch - '0';
    return x * f;
}

const int dirx[] = {1 , 1 , 2 , 2};
const int diry[] = {2 , -2 , 1 , -1};
const int maxn = 51;

queue <pair <int , int> > Q;
queue <int> step;

int vis[maxn][maxn];

int n , m , x , y;

int main() {
    n = read() , m = read();

    Q.push(make_pair(1 , 1));
    step.push(0);
    vis[1][1] = true;

    while (Q.size()) {
        int nowx = Q.front().first , nowy = Q.front().second , nowStep = step.front();
        Q.pop() , step.pop();

        if (nowx == n && nowy == m) {
            cout << nowStep << endl;
            exit(0);
        }

        for (int i = 0 ; i < 4 ; i ++) {
            int nextx = nowx + dirx[i] , nexty = nowy + diry[i];

            if (nextx <= 0 || nexty <= 0 || nextx > n || nexty > m) {
                continue;
            }
            else if (vis[nextx][nexty]) {
                continue;
            }
            else {
                Q.push(make_pair(nextx , nexty));
                step.push(nowStep + 1);
                vis[nextx][nexty] = true;
            }
        }
    }

    puts("No solution!");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值