图的广度优先搜索

图的广度优先搜索基本思想和树的层次遍历差不错。与树的层次遍历不同的是,图中可能包含回路,我们遍历完一个节点,继续进行遍历,可能会回到已经遍历过的节点。为了避免遍历一个节点两次,需要开辟一个bool型的数组来标记该节点是否已经遍历过。

 #include <iostream>  
#include <list>  
#include <queue>  
using namespace std;  
  
//This class represents a directed graph using adjacency list representation  
class Graph  
{  
private:  
    int v;// Number of vertices  
    list<int> *adj;//Pointer to an array containing adjacency lists  
public:  
    Graph(int v);//Constructor  
    void addEdge(int v, int w);//function to add an edge to graph  
    void BFS(int s);//prints BFS tracersal from a given sources  
};  
  
Graph::Graph(int v)  
{  
    this->v = v;  
    adj = new list<int>[v];  
}  
void Graph::addEdge(int v, int w)  
{  
    adj[v].push_back(w);//Add w to v's list  
}  
void Graph::BFS(int s)  
{  
    //Mark all the vertices as not visited  
    bool *visited = new bool[v];  
    for(int i = 0; i < v; i++)  
    {  
        visited[i] = false;  
    }  
      
    //Create a queue for BFS  
    list<int> queue;  
  
    //Mark the current node as visited and enqueue it  
    visited[s] = true;  
    queue.push_back(s);  
  
    //i will be used to get all adjacent vertices fo a vertex  
    list<int>::iterator i;  
    while( !queue.empty() )  
    {  
        //Dequeue a vertex from queue and print it  
        s = queue.front();  
        cout << s << " ";  
        queue.pop_front();  
  
        //Get all adjacent vertices of the dequeued vertex s  
        //If a adjacent has not been visited, then mark it visited  
        //and enqueue it  
        for( i = adj[s].begin(); i != adj[s].end(); i++)  
        {  
            if( !visited[*i] )  
            {  
                visited[*i] = true;  
                queue.push_back(*i);  
            }  
        }  
    }  
    cout << endl;  
}  
  
  
//Driver program to test methonds of graph class  
int main(int argc, char* argv[])  
{  
    //Create a graph given in the above diagram  
    Graph g(4);  
    g.addEdge( 0, 1);  
    g.addEdge( 0, 2);  
    g.addEdge( 1, 2);  
    g.addEdge( 2, 0);  
    g.addEdge( 2, 3);  
    g.addEdge( 3, 3);  
  
    cout <<"Followint is Breadth First Travesal( starting from vertex 2 )\n";  
    g.BFS(2);  
    return 0;  
}  

 

输出结果:

Following is Breadth First Traversal ( starting from vertex 2)

2 0 3 1

posted on 2015-09-28 10:56  joannae  阅读(453)  评论(0编辑  收藏  举报

导航