利用深度遍历算法实现
int getNum(MGraph G) {
int i, count = 0;
for(i = 0; i < G.vexnum; i++)
visited[i] = false;
for(i = 0; i < G.vexnum; i++)
if(!visited[i]) {
count++;
DFS(G, i);
}
return count;
}
测试代码如下:
以下代码以邻接表作为图的存储方式
#include <stdio.h>
#include <stdlib.h>
#define MAXVEX 10
typedef int VertexType;
typedef struct arcNode {
int adjvex;
struct arcNode *next;
} arcNode;
typedef struct vertexNode {
VertexType data;
arcNode *first;
} vertexNode, adjList[MAXVEX];
typedef struct {
adjList adjlist;
int vexnum, arcnum;
} ALGraph;
//邻接表初始化
void createALGraph(ALGraph &G) {
int i, j, k;
arcNode *e;
printf("输入顶点数和边数:\n");
scanf("%d%d", &G.vexnum, &G.arcnum);
for(i = 0; i < G.vexnum; i++) {
scanf("%d", &G.adjlist[i].data);
G.adjlist[i].first = NULL;
}
for(k = 0; k < G.arcnum; k++) {
printf("输入边(vi, vj)上的顶点序号:\n");
scanf("%d%d", &i, &j);
e = (arcNode *)malloc(sizeof(arcNode));
e->adjvex = i;
e->next = G.adjlist[j].first;
G.adjlist[j].first = e;
e = (arcNode *)malloc(sizeof(arcNode));
e->adjvex = j;
e->next = G.adjlist[i].first;
G.adjlist[i].first = e;
}
}
//深度优先遍历
int visited[MAXVEX];
void DFS(ALGraph G, int i) {
arcNode *p;
visited[i] = 1;
p = G.adjlist[i].first;
while(p) {
if(!visited[p->adjvex])
DFS(G, p->adjvex);
p = p->next;
}
}
//求连通分量
int getNum(ALGraph G) {
int i, count = 0; //记录连通分量个数
for(i = 0; i < G.vexnum; i++)
visited[i] = 0;
for(i = 0; i < G.vexnum; i++)
if(!visited[i]) {
count++;
DFS(G, i);
}
return count;
}
int main() {
ALGraph G;
createALGraph(G);
printf("%d", getNum(G));
return 0;
}