(图6-10)Count Connected Components--C语言

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;//返回连通分量的个数
}
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值