理解算法的好方法可以单步调试查看关键变量的变化过程,如head和next,同时画出搜索树分析
#include <iostream> #include <queue> #define SIZE 100005 using namespace std; //搜索是一种暴力的穷举 //分1 - 1 * 2三个方向广搜 queue<int> x; bool vistied[SIZE];//记录点是否搜过 int step[SIZE];//记录当前搜索的步数 int bfs(int n,int k){ int head,next; x.push(n); vistied[n] = true; step[n] = 0;//起始步数为0 while(!x.empty()){ //用队列实现广度优先搜索 //先取出对头 head = x.front(); x.pop(); for (int i=0;i<3;i++) { if (i == 0) { next = head - 1; } else if(i == 1) { next = head + 1; } else next = head * 2; if (next > SIZE || next < 0) { continue; } //判重,若没有搜过则入队列 if (!vistied[next]) { x.push(next); step[next] = step[head] + 1; vistied[next] = true; } if (next == k) { return step[next]; } } } } int main(){ int n,k; cin>>n>>k; if (n > k) cout<<n-k<<endl; else cout<<bfs(n,k)<<endl; return 0; }
本文通过一个具体的示例介绍了如何使用广度优先搜索(BFS)算法来解决寻找两个整数之间的最短路径问题。文章详细展示了算法的实现过程,并使用了队列来组织待搜索的状态,通过记录每个状态的访问情况和到达该状态所需的步骤,最终找到了从初始状态到目标状态的最短路径。
1576

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



