版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27855219/article/details/53206611
求无向图连通分量个数方法:
基于DFS,从某一顶点出发遍历图,for循环,改变起始顶点,count计数。
代码如下:
void DFSTraverse(ALGraph G){ //深度遍历图
void DFS(ALGraph G,int i);
int count=0;
for(int i = 0; i < G.vexnum; i++) //初始化visited[]数组,设为都未访问过
visited[i]=0;
for(int j = 0; j < G.vexnum; j++){
if(!visited[j]){
DFS(G,j);
count++;
} //未访问,则访问结点
}
printf("连通分量的个数:%d \n",count);
}//DFSTraverse
void DFS(ALGraph G,int i)
{
printf("%d ",i);
fflush(stdout);
visited[i]=1;
ArcNode * p;
p=G.adjlist[i].firstarc;//边表头指针
while (p!=NULL) //边表
{
if (!visited[p->adjvex])
DFS(G,p->adjvex);
p=p->nextarc;
}//while
}