蓝桥杯算法练习笔记(10)__广度优先搜索 BFS
发布日期:2021-04-30 21:05:37 浏览次数:105 分类:精选文章

本文共 2152 字,大约阅读时间需要 7 分钟。

?????? (BFS)

?????? (BFS) ?????????????????????????????? (DFS) ???BFS ????????????

?? (Queue)

????????? (FIFO) ?????????BFS?????C++???????????

#include 
#include
using namespace std;
int main() {
queue
q;
q.push(1);
q.push(2);
q.push(3);
cout << q.front() << endl;
q.pop();
return 0;
}

???????

????????m?????????1?m??????n????????????1??????????????????

#include 
#include
using namespace std;
int main() {
int n, m;
cin >> n >> m;
queue
q;
for(int i = 1; i <= n; i++) {
q.push(i);
}
int cur = 1;
while(q.size() > 1) {
int x = q.front();
q.pop();
if(cur != m) {
q.push(x);
cur++;
} else {
cur = 1;
}
}
cout << q.front() << endl;
return 0;
}

????

BFS?DFS????????????????????????BFS?????????????????????????????

???????

?????????A??B??????????????????+1?????????-1???????*2??????BFS???????A?B?

#include 
#include
#include
using namespace std;
bool vis[100];
int main() {
int n, A, B, now, step;
cin >> n >> A >> B;
queue
> q;
q.push(make_pair(A, 0));
vis[A] = true;
while(!q.empty()) {
now = q.front().first;
step = q.front().second;
q.pop();
if(now == B) {
cout << step << endl;
break;
}
if(now + 1 <= n && !vis[now + 1]) {
q.push(make_pair(now + 1, step + 1));
vis[now + 1] = true;
}
if(now - 1 >= 0 && !vis[now - 1]) {
q.push(make_pair(now - 1, step + 1));
vis[now - 1] = true;
}
if(now * 2 <= n && !vis[now * 2]) {
q.push(make_pair(now * 2, step + 1));
vis[now * 2] = true;
}
}
return 0;
}

???

?????????BFS???????????????????????????????????

??????

??????????BFS???????????????????????????????????

?????

????????BFS???????????????????????????????????

???????????BFS???????????????

上一篇:基本的Dos命令(cmd窗口)
下一篇:HTML基础知识点总结一

发表评论

最新留言

表示我来过!
[***.240.166.169]2026年05月25日 19时57分43秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章