POJ 3278 用队列实现BFS搜索

理解算法的好方法可以单步调试查看关键变量的变化过程,如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; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值