广度优先搜索

一 广度优先搜索

  个人感觉图的广度优先搜索算法同二叉树的层序遍历算法有异曲同工之妙,均用队列实现。

    层序遍历将根节点首先放入队列,并开始检索队列:首先取出队列中的节点访问,并将该节点的子节点均添加至队列

    广度优先搜索将某顶点放入队列,并开始检索队列:首先取出队列中的顶点访问,并在该顶点的未访问过的邻接顶点

添加至队列

二 代码表示

  简单的图。

  1 广度优先算法

 1 void BreadthFirstSearch(Vertex *graph, int VertexNum)
 2 {
 3     queue<int> vertexQueue;
 4 
 5     cout << "广度遍历:" << endl;
 6     vertexQueue.push(0); // 先将某个顶点放入队列
 7     graph[0].color = GRAY;
 8     while (!vertexQueue.empty())
 9     {
10         int uIdx = graph[vertexQueue.front()].idx;
11         vertexQueue.pop();
12         cout << uIdx << endl; // 访问pop出的顶点
13         Vertex *pre = &graph[uIdx];
14         while (pre->next)
15         {
16             int vIdx = pre->next->idx;
17             if (graph[vIdx].color == WHITE)
18             {
19                 vertexQueue.push(vIdx); // 将未访问过的邻接节点添加至队列
20                 graph[vIdx].color = GRAY;
21             }
22             pre = pre->next;
23         }
24         graph[uIdx].color = BLACK;
25     }
26 }

 

posted @ 2015-07-19 17:49  yoleimei  阅读(166)  评论(0编辑  收藏  举报