图的数据结构为邻接链表adjacency list。
listVertex是一个储存Vertex* 顶点类指针的vector类型的STL;在Vertex类中有一个类成员nextEdgeNode,他是储存pair类型的vector容器;数对pair的first表示边指向的顶点序号,second表示边的序号。
四个函数都只有一个参数,在声明时提供了默认的参数值-1;参数表示起始顶点的编号
先放一个测试用的图、有向图的邻接链表、无向图的邻接链表。
以下是有向图的BFS
1 void Graph::BFSListO(intstartFrom) {2 /*the principle is to firstly choose a random vertex, if it has 0 out degree, then choose the first3 unvisited vertex in the list; moreover,if one way is exhausted to continue,also push the first univisited vertex4 in the list to the queue*/
5 cout << "BFS of oriented Adjacey List:" <
9 while (listVertex[rdm]->nextEdgeNode.empty()) {10 rdm = rand() % sze;//randomly choose a vertex whose out degree is not 0
11 }12 queuemyQueue;13 if(startFrom==-1)//default treatment is random choose
14 myQueue.push(listVertex[rdm]);15 else {//designated choose
16 myQueue.push(listVertex[startFrom-1]);17 }18 while (!myQueue.empty()) {//travel through until there is nothing in the queue
19 Vertex* V =myQueue.front();20 if (V->color == 0) {21 V->color = 1; //O black(unvisited) & 1 white(visited)//V visited white 1
22 cout << "Vertex visit