#include <iostream>using namespace std;typedef char vertextype;typedef int edgetype; #define Maxvex 100#define Infinity 1000#include<queue>int visited[100];class mgraph{public:vertextype vexs[maxvex];edgetype Arc[maxvex] [Maxvex];int numvertexs,numedges;//Figure's vertex number and the number of edges of the graph mgraph (const int &V,CONST int &e): Numvertexs (v), Numedges (e) {}void creategraph ();//create diagram structure void displaygraph ();//show graph structure void DFS (int i);//Sub-function with depth precedence traversal void dfstraverse (); void Bfstraverse ();//define Breadth Traversal algorithm};void mgraph::creategraph () {cout<< "Please enter the element type value of the vertex, enter the number of" <<numvertexs< <endl;for (int i=0;i<numvertexs;++i) {cin>>vexs[i];} Cin.clear ();cout<< "Please assign a value to the adjacency matrix, the size of the matrix:" <<numvertexs<< "*" <<numvertexs<<endl;for ( int i=0;i<numvertexs;++i) {for (int j=0;j<numvertexs;++j) {cin>>arc[i][j];}}} void Mgraph::d isplaygraph () {cout<< "output is the element in the vertex" <<endl;for (int i=0;i<numvertexs;++i) {cout<< vexs[i]<< "";} cout<<endl;for (int i=0;i<numvertexs;++i) {for (int j=0;j<numvertexs;++j) {cout<<arc[i][j]<< ' \ t ';} Cout<<endl;}} The following defines the depth-first function void Mgraph::D fs (int i) {int j;visited[i]=true;cout<< "depth-First output node information" <<vexs[i]<<endl; for (J=0;J<NUMVERTEXS;++J) {if (Arc[i][j]==1&&!visited[j]) DFS (j);}} void Mgraph::D fstraverse () {int i;for (i=0;i<numvertexs;++i) {visited[i]=0;} for (I=0;i<numvertexs;++i) {if (!visited[i]) DFS (i);}} void Mgraph::bfstraverse () {int i,j;queue<int> q;for (i=0;i<numvertexs;++i) visited[numvertexs]=0;for (i=0;i <numvertexs;++i) {if (!visited[i]) {visited[i]=1;cout<< "breadth-traversed node information is" <<vexs[i]<<endl;q.push (i ); while (!q.empty ()) {int K;k=q.front (); Q.pop (); for (j=0;j<numvertexs;++j) {if (Arc[i][j]==1&&!visited[j] {visited[j]=1;cout<< "breadth traversal of the node information is" <<vexs[i]<<endl;q.push (j);}}}}} int main () {mgraph G (4,5); G.creategraph (); G.displaygraph ();//g.dfstraverse (); G.bfstraverse (); System ("pause"); return 0;}
The creation of adjacency matrix of C + + implementation graph and its depth-first traversal and breadth-first traversal