《算法导论》中给出的对图进行广度优先搜索算法
Posted 计算机科学部落
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《算法导论》中给出的对图进行广度优先搜索算法相关的知识,希望对你有一定的参考价值。
《算法导论》中给出的对图进行广度优先搜索算法
是遍历形的方法之一。该算法首先发现距离k处的所有与 “ ” 相连的顶点。然后再发现距离 的 处发现顶点,以此类推。 中给出的算法使用“颜色”的概念来检查是否完全或部分或未发现某个顶点。它还跟踪顶点 与源点 的距离。
算法
BFS(G,s)
1 for each vertex u in G.V - {s}
2 u.color = white
3 u.d = INF
4 u.p = NIL
5 s.color = green
6 s.d = 0
7 s.p = NIL
8 Q = NULL
9 ENQUEUE(Q,s)
10 while Q != NULL
11 u = DEQUEUE(Q)
12 for each v in G.Adj[u]
13 if v.color == white
14 v.color = green
15 v.d = u.d + 1
16 v.p = u
17 ENQUEUE(Q,v)
18 u.color = dark_green
它产生一个以根s包含所有可到达顶点的“广度优先的树”。我们看一个简单的BFS如何遍历例子,如下图所示。
原始图
开始遍历
遍历第一层节点
第一层遍历完成
算法实现
// CPP program to implement BFS as per CLRS algorithm.
#include <bits/stdc++.h>
using namespace std;
// Declaring the vectors to store color, distance and parent
vector<string> color;
vector<int> dist;
vector<int> parent;
/*
This function adds an edge to the graph.
It is an undirected graph. So edges are
added for both the nodes.
*/
void addEdge(vector<int> g[], int u, int v)
{
g[u].push_back(v);
g[v].push_back(u);
}
/* This function does the Breadth First Search*/
void BFSSingleSource(vector<int> g[], int s)
{
// The Queue used for the BFS operation
queue<int> q;
// Pushing the root node inside the queue
q.push(s);
/* Distance of root node is 0 & color
is gray as it is visited partially now */
dist[s] = 0;
color[s] = "green";
/* Loop to traverse the graph. Traversal
will happen traverse until the queue is
not empty.*/
while (!q.empty())
{
/* Extracting the front element(node)
and poping it out of queue. */
int u = q.front();
q.pop();
cout << u << " ";
/* This loop traverses all the child nodes of u */
for (auto i = g[u].begin(); i != g[u].end(); i++)
{
/* If the color is white then the said node
is not traversed. */
if (color[*i] == "white")
{
color[*i] = "green";
dist[*i] = dist[u] + 1;
parent[*i] = u;
/* Pushing the node inside queue
to traverse its children. */
q.push(*i);
}
}
/* Now the node u is completely traversed
and color is changed to black. */
color[u] = "dark_green";
}
}
void BFSFull(vector<int> g[], int n)
{
// Initially all nodes are not traversed.
// Therefore, the color is white.
color.assign(n, "white");
dist.assign(n, 0);
parent.assign(n, -1);
// Calling BFSSingleSource() for all white vertices.
for (int i = 0; i < n; i++)
if (color[i] == "white")
BFSSingleSource(g, i);
}
// Driver Function
int main()
{
// Graph with 7 nodes and 6 edges.
int n = 7;
// The Graph vector
vector<int> 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);
BFSFull(g, n);
cout << endl;
return 0;
}
程序输出
0 1 2 3 4 5 6
以上是关于《算法导论》中给出的对图进行广度优先搜索算法的主要内容,如果未能解决你的问题,请参考以下文章