本文共 1783 字,大约阅读时间需要 5 分钟。
BFS算法用于解决从起点到同一位置的最短路径问题,步数最多是多少。牛的位置固定,起点即为目标点。以下是优化后的代码和详细解释:
一、题目:
告诉你和一头牛的位置,牛是不动的,问最多走几步可以抓住这头牛。走步有三种方式:向前走1步(step +1)、向后走1步(step -1)和步数乘以2(step * 2)。
二、广搜的一般步骤:
BFS算法采用队列来逐层扩展,找到最少的步骤数。初始化队列,将起点加入队列并标记访问。每次从队首取出元素,生成所有可能的下一步,检查是否合法且未被访问过,若合法则加入队列。
三、代码:
```cpp#include#include using namespace std;bool vis[100005];const int max_num = 100000;int main() { int N, K; scanf("%d %d", &N, &K); if (N == K) { printf("0\n"); return 0; } queue > q; q.push({N, 0}); vis[N] = true; while (!q.empty()) { auto current = q.front(); q.pop(); int now = current.first; int step = current.second; if (now == K) { printf("%d\n", step); return 0; } if (now + 1 <= max_num && !vis[now + 1]) { if (now + 1 == K) { printf("%d\n", step + 1); return 0; } q.push({now + 1, step + 1}); vis[now + 1] = true; } if (now - 1 >= 0 && !vis[now - 1]) { if (now - 1 == K) { printf("%d\n", step + 1); return 0; } q.push({now - 1, step + 1}); vis[now - 1] = true; } if (now * 2 <= max_num && !vis[now * 2]) { if (now * 2 == K) { printf("%d\n", step + 1); return 0; } q.push({now * 2, step + 1}); vis[now * 2] = true; } } return 0;}
通过直接判断到达目标点而不是将目标点加入队列,显著减少了处理时间和队列操作次数,提升了算法的性能和效率。
转载地址:http://nqwn.baihongyu.com/