//////////////////////////////////////////////////////////adjacency matrix of graphs for DFS and BFS////////////////////////////////////////////////////////#include <iostream>#include<stdlib.h>#include<queue>#defineMaxvertexnum 100//maximum number of vertices//#define INFINITY 0//Infinity is set to the maximum value of the unsigned integertypedefCharVertextype;//vertex type set to character typetypedefintEdgetype;///the weight value of the edge is set to reshapeenumGRAPHTYPE{DG, UG, DN, UN};//Forward Graph, non-direction graph, mesh graph, non-meshusing namespaceStd;typedefstruct{vertextype vertices[maxvertexnum];//Vertex TableEdgetype Edges[maxvertexnum][maxvertexnum];//adjacency matrix, or edge table intN, E;//number of vertices n and number of edges e enumGraphtype GType;} Mgraph;voidCreatemgraph (Mgraph *G) { intI, J, K, W; G->gtype = UN;/*undirected Network no-map*/cout<<"Please enter the number of vertices and the number of sides (input format: Top count, number of sides):"<<Endl; CIN>> g->n >> g->e;/*Enter the number of vertices and the number of edges*/cout<<"Please enter the vertex information (input format is: Vertex number <CR>):"<<Endl; for(i =0; I < g->n; i++) Cin>> & (G->vertices[i]);/*entering vertex information, creating a vertex table*/ for(i =0; I < g->n; i++) for(j =0; J < g->n; J + +) G->EDGES[I][J] =0;/*initializing adjacency matrices*/cout<<"Enter the ordinal and weight of the two vertices corresponding to each edge, in the following format: I, J, W:"<<Endl; for(k =0; K < g->e; k++) {cin>> I >> J >> W;/*Enter the right on the edge of the e bar to establish the adjacency matrix*/G->EDGES[I][J] =W; G->edges[j][i] = W;/*because the adjacency matrix of the non-facing graph is symmetric*/ }}voidPrint (Mgraph *G) {cout<<" "; for(inti =0; I < g->n; i++) cout<< G->vertices[i] <<" "; cout<<Endl; for(inti =0; I < g->n; i++) {cout<< G->vertices[i] <<" "; for(intj =0; J < g->n; J + +) {cout<< G->edges[i][j] <<" "; } cout<<Endl; }}//graph of adjacency matrix storage-DFSBOOLvisited[ -] = {false };voidDFS (Mgraph *g,intk) {cout<< G->vertices[k] <<" "; VISITED[K]=true; for(inti =0; I < g->n; i++) { if(G->edges[k][i] = =1&& Visited[i] = =false) {DFS (G, i); } }}//graph of adjacency matrix storage-BFSvoidBFS (Mgraph *g,intk) { BOOLvisited[ -] = {false }; Queue<int>Q; for(inti =0; I < g->n; i++) Visited[i]=false; if(Visited[k] = =false)//If the node is not accessible{Visited[k]=true; cout<<"visit vertex:"<< G->vertices[k] <<Endl; Q.push (k); //u into queue } while(!Q.empty ()) { intt =Q.front (); Q.pop (); for(intW =0; W < g->n; w++) { if(G->edges[t][w]! =0&& Visited[w] = =false) {Visited[w]=true; cout<<"visited Vertex:"<< G->vertices[w] <<Endl; Q.push (w); } } }}intMain () {mgraph*g =Newmgraph; Createmgraph (G); Print (G); cout<<Endl; DFS (G,0); //BFS (G, 0);System"Pause"); return 0;}
Test:
Data Structure (12)--DFS and BFS for the adjacency matrix of the graph