Write a function to count the number of connected components in a given graph.
函数接口定义:
int CountConnectedComponents( LGraph Graph );
where LGraph is defined as the following:
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
The function CountConnectedComponents is supposed to return the number of connected components in the undirected Graph.
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef enum {false, true} bool;
#define MaxVertexNum 10 /* maximum number of vertices */
typedef int Vertex; /* vertices are numbered from 0 to MaxVertexNum-1 */
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
LGraph ReadG(); /* details omitted */
int CountConnectedComponents( LGraph Graph );
int main()
{
LGraph G = ReadG();
printf("%d\n", CountConnectedComponents(G));
return 0;
}
/* Your function will be put here */
输入样例:
8 6
0 7
0 1
2 0
4 1
2 4
3 5
输出样例:
3
代码:
void dfs(LGraph Graph, int visited[], Vertex v)
{
visited[v] = 1;//标记当前顶点 v 已访问
PtrToAdjVNode p = Graph->G[v].FirstEdge;//获取顶点 v 的邻接链表头指针
while (p)
{
if (visited[p->AdjV] == 0)//如果邻接顶点 p->AdjV 还未被访问
dfs(Graph, visited, p->AdjV);//递归访问该邻接顶点的连通分量
p = p->Next;//继续遍历顶点 v 的邻接链表
}
}
int CountConnectedComponents(LGraph Graph)
{
int count = 0;//计数连通分量个数
int visited[MaxVertexNum];//标记数组,初始化为0
for (int i = 0; i < Graph->Nv; i++)
visited[i] = 0;//初始化所有顶点为未访问状态
for (int v = 0; v < Graph->Nv; v++)
{
if (visited[v] == 0)//如果顶点 v 未被访问过
{
count++;//新的连通分量计数加一
dfs(Graph, visited, v);//访问以顶点 v 开始的连通分量
}
}
return count;//返回连通分量的个数
}