已知无向图G=(V,E),给出求图G连通分量的个数的算法。
思想:在深度优先遍历时,调用DFS的次数就是连通分量的个数。
代码:
typedef char GElemType;
typedef struct ArcNode{
int adjvex; //该边所指向的顶点的位置
struct ArcNode *next;//指向下一条边的指针
}ArcNode;
//顶点的结点结构
typedef struct VNode{
GElemType data;//顶点信息、
ArcNode *first;//指向第一条依附该顶点的边的指针
}VNode,AdjList[MVNum];//AdjList表示邻接表类型
//图的结构定义
typedef struct{
VNode *vertices; //定义一个数组vertices,是vertex的复数形式
int vexNum,arcNum; //图的当前顶点数和弧数
}ALGraph;
//深度优先遍历 ,图的邻接表表示法
void DFS(ALGraph* G,int v,bool *vistied){
visited[v]=true; //标记访问顶点
ArcNode *arc=G->vertices[v].first;//取第一条边
while(arc!=NULL){
if(visited[arc->adjvex]==false){
DFS(G,arc->adjvex,visited);//递归访问
}
arc=arc->next;
}
}
//计算连通分量个数
int getConecetedComponents(ALGraph *G){
//申请visited数组
bool *visited = (bool*)malloc(sizeof(bool)*G->vexNum);
for(int i=0;i<G.vexNum;i++){
visited[i]=false;
}
int k=0;//用了记录连通分量个数
for(int i=0;i<.G.vexNum;i++){
if(visited[i]==false){
k++;
DFS(G,i,visited);
}
}
free(visited);
return k;
}