使用向量和队列实现BFS,按照CLRS算法在C程序中的实现

使用向量和队列实现bfs,按照clrs算法在c程序中的实现

在CLRS书中,BFS算法使用向量和队列来描述。我们必须使用C++ STL来实现该算法。首先让我们看一下算法。

算法

BFS(G, s) −

begin   for each vertex u in G.V - {s}, do      u.color := white      u.d := infinity      u.p := NIL   done   s.color := green   s.d := 0   s.p := NIL   Q := NULL   insert s into Q   while Q is not null, do      u = delete from Q      for each v in adjacent to u, do         if v.color = white            v.color := green            v.d := u.d + 1            v.p := u            insert v into Q         end if      done      u.color = dark_green   doneend

Example

的中文翻译为:

示例

#include#include#includeusing namespace std;vector colour;vector dist;vector par;void addEdge(vector  g[], int u, int v) { //add edge to form the graph   g[u].push_back(v);   g[v].push_back(u);}void BFS(vector  g[], int s) {   queue q;   q.push(s); //insert source   dist[s] = 0;   colour[s] = "gray";   while (!q.empty()) {      int u = q.front(); //top element from queue, then delete it      q.pop();      cout << u << " ";      for (auto i = g[u].begin(); i != g[u].end(); i++) {         if (colour[*i] == "white") { //white is unvisited node            colour[*i] = "gray"; //gray is visited but not completed            dist[*i] = dist[u] + 1;            par[*i] = u;            q.push(*i);         }      }      colour[u] = "black"; //black is completed node   }}void BFSAlgo(vector  g[], int n) {   colour.assign(n, "white"); //put as unvisited   dist.assign(n, 0);   par.assign(n, -1);   for (int i = 0; i < n; i++)      if (colour[i] == "white")   BFS(g, i);}int main() {   int n = 7;   vector  g[n];   addEdge(g, 0, 1);   addEdge(g, 0, 2);   addEdge(g, 1, 3);   addEdge(g, 1, 4);   addEdge(g, 2, 5);   addEdge(g, 2, 6);   BFSAlgo(g, n);}

输出

0 1 2 3 4 5 6

以上就是使用向量和队列实现BFS,按照CLRS算法在C程序中的实现的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444487.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 21:34:51
下一篇 2025年12月17日 21:35:07

相关推荐

  • Laravel开发注意事项:合理使用缓存与队列

    Laravel是一款非常流行的PHP开发框架,它提供了丰富的功能和便捷的开发方式,能够帮助开发人员快速构建稳定可靠的Web应用程序。在Laravel开发过程中,合理使用缓存与队列是十分重要的,本文将介绍一些注意事项以帮助开发人员更好地利用缓存与队列。 一、合理使用缓存 缓存的定义与作用缓存是一种将经…

    2025年11月1日
    000

发表回复

登录后才能评论
关注微信