【每日一题】Catch That Cow

Catch That Cow

题意:

找牛,三种走法,1.向前一步;2.后退一步;3.位置翻一倍。给农夫的位置和牛的位置,求最小步数

题解:

可以抽象为搜索问题,也属于水题吧,整体难度不大

个人问题:

没有一把过,问题在于没有考虑数组越界的情况。没有卡最大值的情况,就是农夫的位置不能大于100000

代码:
///Catch That Cow
#include<iostream>
#include<cstdlib>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<stack>
#include<queue>
#include<iomanip>
#include<map>
#include<set>
#include<functional>
using namespace std;
struct dataa {
    int x, k;
}now, well;
int flag[100100],n,m;
int BFS(int a,int B) {
    memset(flag, 0, sizeof(flag));///标记点是否走过的地图
    dataa A;
    A.x = a;
    A.k = 0;///初始化
    queue<dataa> Q;
    Q.push(A);///恶梦的开始
    flag[A.x] = 1;///标记初始点已经走过了
    while (!Q.empty()) {
        now = Q.front();///处理第一个数据 
        Q.pop();///抛弃第一个数据
        if (now.x == B)///判断是否到达目的地
            return now.k;
        for (int i = 0; i < 3; i++) {
            if (i == 0) well.x = now.x + 1;
            if (i == 1) well.x = now.x - 1;
            if (i == 2) well.x = now.x * 2;
            if (well.x >= 0 && well.x <=100000 && flag[well.x] == 0) {
                well.k = now.k + 1;///总步数加1
                flag[well.x] = 1;///标记初始点已经走过了,顺便标记这个点是第几步走的
                Q.push(well);///压进队列
            }
        }
    }
}
int main() {
    cin >> n >> m;
    cout << BFS(n, m) << endl;
    return 0;
}
写在最后:

推荐两篇博客个人关于搜索的总结关于这个题一位同学的题解

发布了41 篇原创文章 · 获赞 16 · 访问量 1462

猜你喜欢

转载自blog.csdn.net/weixin_43824551/article/details/104504897