#define MaxVertexNum 120 #include "stdio.h" #include <stdlib.h> #include <queue> using namespace std; typedef int WeightType; typedef int DataType; typedef int Vertex; typedef struct GNode* PtrToGNode; struct GNode { int Nv; int Ne; WeightType G[MaxVertexNum][MaxVertexNum]; DataType Data[MaxVertexNum]; }; typedef PtrToGNode MGraph; typedef struct ENode* PtrToENode; struct ENode { Vertex V1, V2; WeightType Weight; }; typedef PtrToENode Edge; MGraph createGraph( int VertexNum ) { Vertex V, M; MGraph Graph; Graph = (MGraph) malloc(sizeof(struct GNode)); Graph->Ne = 0; Graph->Nv = VertexNum; for (V = 0; V<VertexNum; V++) { for(M = 0; M<VertexNum; M++) { Graph->G[V][M] = 0; } } return Graph; } void InsertEdge(MGraph Graph, Edge E) { Graph->G[E->V1][E->V2] = E->Weight; //undirected graph Graph->G[E->V2][E->V1] = E->Weight; } MGraph buildGraph() { MGraph Graph; int Nv; Vertex V; Edge E; scanf( "%d", &Nv ); Graph = createGraph(Nv); scanf( "%d", &(Graph->Ne) ); if(Graph->Ne){ E = (Edge) malloc(sizeof(struct ENode)); for(int i=0; i<Graph->Ne; i++) { scanf("%d %d", &(E->V1), &(E->V2)); E->Weight = 1; InsertEdge(Graph, E); } } /* for(V = 0; V < Graph->Nv; V++) { scanf("%d", Graph->Data[V]); } */ return Graph; } int Visted[MaxVertexNum] = {0}; void reset(int a[], int bound) { for (int i=0;i<bound;i++) { a[i] = 0; } } void DFS(MGraph Graph, Vertex V) { printf("%d ", V); Visted[V] = 1; Vertex M; for (M = 0; M<Graph->Nv; M++) { if (Graph->G[V][M] and !Visted[M]) { DFS(Graph, M); } } } void BFS(MGraph Graph, Vertex V) { queue< Vertex > Q; Vertex E; printf("%d ", V); Visted[V] = 1; Q.push(V); while(!Q.empty()) { E = Q.front(); Q.pop(); for(Vertex W = 0; W < Graph->Nv; W++) { if(!Visted[W] and Graph->G[E][W] == 1) { printf("%d ", W); Visted[W] = 1; Q.push(W); } } } } void search(MGraph Graph, Vertex V, void(*f)(MGraph Graph, Vertex V)) { reset(Visted, MaxVertexNum); for(V=0; V<Graph->Nv; V++) { if (!Visted[V]) { printf("{ "); f(Graph, V); printf("}\n"); } } } int main() { MGraph Graph = buildGraph(); Vertex V; search(Graph, V, DFS); search(Graph, V, BFS); }
原文:https://www.cnblogs.com/acoccus/p/10723701.html