骑士游历

问题描述

这里写图片描述

输入

输入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!");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值