程序中graph.h是图存储结构的“算法库”中的头文件,详情请单击链接…
main.cpp
#include <stdio.h> #include <malloc.h> #include "graph.h" int visited[MAXV]; //定义存放节点的访问标志的全局数组 void DFS(ALGraph *G, int v) { ArcNode *p; int w; visited[v]=1; printf("%d ", v); p=G->adjlist[v].firstarc; while (p!=NULL) { w=p->adjvex; if (visited[w]==0) DFS(G,w); p=p->nextarc; } } //采用深度优先搜索遍历非连通无向图 void DFS1(ALGraph *G) { int i; for (i=0; i<G->n; i++) if (visited[i]==0) DFS(G,i); } int main() { int i; ALGraph *G; int A[8][8]= { {0,1,0,1,0,0,0,0}, {1,0,1,0,0,0,0,0}, {0,1,0,1,1,0,0,0}, {1,0,1,0,1,0,0,0}, {0,0,1,1,0,0,0,0}, {0,0,0,0,0,0,1,0}, {0,0,0,0,0,1,0,1}, {0,0,0,0,0,0,1,0}, }; ArrayToList(A[0], 8, G); for (i=0; i<G->n; i++) visited[i]=0; //访问标志数组初始化 printf(" 非连通图的广度优先遍历:\n"); DFS1(G); return 0; }
运行结果: