原题连接:poj-3278
题目大意:农夫和牛都在数轴上,农夫位于起始点N处,牛位于K点处,农夫想要抓到牛。农夫有两种移动方式:1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛不动,农夫最短多长时间抓到牛?
题目思路:BFS(广度优先搜索),建立队列,给节点分层,一层一层搜索下去,需要注意得就是要去重。
题目代码:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <queue>
using namespace std;
const int N = 1000000;
int map[1000020];
int n, k;
struct node
{
int x, step;
};
int check(int x)
{
if (x < 0 || x >= N || map[x])
return 0;
return 1;
}
int bfs(int x)
{
queue<node> Q;
node a, next;
a.x = x;
a.step = 0;
Q.push(a);
while (!Q.empty())
{
a = Q.front();
Q.pop();
if (a.x == k)
return a.step;
next.x = a.x + 1;
if (check(next.x))
{
next.step = a.step + 1;
map[next.x] = 1;
Q.push(next);
}
next.x = a.x - 1;
if (check(next.x))
{
next.step = a.step + 1;
map[next.x] = 1;
Q.push(next);
}
next.x = a.x * 2;
if (check(next.x))
{
next.step = a.step + 1;
map[next.x] = 1;
Q.push(next);
}
}
return -1;
}
int main()
{
int ans;
scanf_s("%d%d", &n, &k);
memset(map, 0, sizeof(map));
ans = bfs(n);
printf("%d\n", ans);
return 0;
}
欢迎在评论区留言或者私信。
努力努力再努力x
本文解析了使用广度优先搜索(BFS)算法解决农夫在数轴上追牛的问题,通过队列实现节点分层搜索,确保路径最短,同时介绍了去重策略避免重复计算。
1590

被折叠的 条评论
为什么被折叠?



