06-图1-列出连通集

给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集。假设顶点从0到N−1编号。进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。

输入样例:
8 6
0 7
0 1
2 0
4 1
2 4
3 5

输出样例:
{ 0 1 4 2 7 }
{ 3 5 }
{ 6 }
{ 0 1 2 7 4 }
{ 3 5 }
{ 6 }

解题思路:首先先建立图,然后再对所建立的图进行DFS,BFS便可找到连通的边.

BFS的本质思想使用一个队列来储存图的下标.
这里的DFS和BFS都值得借鉴.
特别要注意的是BFS所用到的思想并不是递归.

#include<cstdio>

#define N 15

int G[N][N],Nv,Ne;
bool Visited[N];

void InitVisit()
{
    for(int i=0;i<N;i++)
        Visited[i] = false;
}

void DFS(int V)
{
    Visited[V] = true;
    printf("%d ",V);
    for(int i=0;i<Nv;i++)
    {
        if(!Visited[i]&&G[V][i])
            DFS(i);
    }
}

void ListComponentsWithDFS()
{
    for(int i=0;i<Nv;i++)
    {
        if(!Visited[i])
        {
            printf("{ ");
            DFS(i);
            printf("}\n");
        }
    }
}

void BFS(int V)
{
    const int MAX_SIZE = 100;
    int Queue[MAX_SIZE];
    int first = -1, last = -1;

    Queue[++last] = V;      //入队
    Visited[V] = true;
    while (first < last)    //当队不为空时
    {
        int F = Queue[++first];     //出队
        printf("%d ", F);
        for (int i = 0; i < Nv; i++)
        {
            if (G[F][i] && !Visited[i])
            {
                Queue[++last] = i;      //入队
                Visited[i] = true;
            }
        }
    }
}

void ListComponentsWithBFS()
{
    for(int i=0;i<Nv;i++)
    {
        if(!Visited[i])
        {
            printf("{ ");
            BFS(i);
            printf("}\n");
        }
    }
}

void CreateGraph()
{
    int v1,v2;

    scanf("%d %d",&Nv,&Ne);
    for(int i=0;i<Nv;i++)
    {
        for(int j=0;j<Nv;j++)
        {
            G[i][j] = 0;
        }
    }
    for(int i=0;i<Ne;i++)
    {
        scanf("%d %d",&v1,&v2);
        G[v1][v2] = 1;
        G[v2][v1] = 1;
    }
}

int main()
{
    CreateGraph();
    InitVisit();
    ListComponentsWithDFS();
    InitVisit();
    ListComponentsWithBFS();
}












### 关于PTA平台上的连通集实现 #### 一、连通集的概念及其意义 在一个无向中,如果任意两个顶点之间都存在一条路径相连,则称这个为连通。而连通分量是指一个非连通中的极大连通子[^1]。 为了在程序设计竞赛或者实际开发中解决连通性问题,通常会采用并查集(Union-Find Set)、深度优先搜索(DFS)或广度优先搜索(BFS)来查找和处理这些连通分量。 --- #### 二、数据结构的选择与定义 针对连通集的实现,常见的两种方式如下: ##### 1. 并查集(Disjoint Set Union, DSU) 并查集是一种用于管理集合的数据结构,支持快速查询某个元素属于哪个集合以及合并两个集合的功能。其核心操作包括 `find` 和 `union`。 ###### 定义: ```c++ class DisjointSet { private: vector<int> parent; public: DisjointSet(int size) : parent(size) { for (int i = 0; i < size; ++i) { parent[i] = i; } } int find_set(int x) { // 路径压缩优化 if (parent[x] != x) { parent[x] = find_set(parent[x]); } return parent[x]; } void union_set(int x, int y) { // 按秩合并优化省略 int fx = find_set(x); int fy = find_set(y); if (fx != fy) { parent[fy] = fx; } } }; ``` 通过上述代码,我们可以高效地维护一组不相交的集合,并能迅速判断两节点是否在同一连通集中[^2]。 --- ##### 2. 使用邻接表/邻接矩阵配合 DFS 或 BFS 另一种方法是利用的存储形式——邻接表或邻接矩阵,结合深度优先搜索(DFS)或广度优先搜索(BFS),逐一访问未被标记过的节点,从而找到所有的连通分量。 ###### 邻接表定义: ```cpp #include <vector> using namespace std; // 创建邻接表 void add_edge(vector<vector<int>>& adj_list, int u, int v) { adj_list[u].push_back(v); adj_list[v].push_back(u); // 如果是有向则去掉这一句 } ``` ###### DFS 实现: ```cpp void dfs(const vector<vector<int>>& graph, vector<bool>& visited, int node) { visited[node] = true; for (const auto& neighbor : graph[node]) { if (!visited[neighbor]) { dfs(graph, visited, neighbor); } } } int count_connected_components_dfs(const vector<vector<int>>& graph) { int n = graph.size(); vector<bool> visited(n, false); int components = 0; for (int i = 0; i < n; ++i) { if (!visited[i]) { dfs(graph, visited, i); components++; } } return components; } ``` ###### BFS 实现: ```cpp #include <queue> int bfs_count_connected_components(const vector<vector<int>>& graph) { int n = graph.size(); vector<bool> visited(n, false); queue<int> q; int components = 0; for (int i = 0; i < n; ++i) { if (!visited[i]) { q.push(i); visited[i] = true; while (!q.empty()) { int current_node = q.front(); q.pop(); for (auto& neighbor : graph[current_node]) { if (!visited[neighbor]) { visited[neighbor] = true; q.push(neighbor); } } } components++; } } return components; } ``` 以上代码展示了如何基于邻接表使用 DFS/BFS 来统计连通分量的数量[^3]。 --- #### 三、具体应用场景分析 当面对大规模稀疏时,推荐使用 **邻接表+DFS/BFS** 方法;而对于稠密或需要频繁执行连接性和断开操作的情况,应考虑使用 **并查集** 结构[^4]。 --- ### 性能对比总结表格 | 特性 | 并查集 | DFS / BFS | |-------------------|----------------------------|---------------------------| | 时间复杂度 | O(α(N)) | O(V+E),其中 α 是反阿克曼函数 | | 空间复杂度 | 较低 | 取决于递归栈深或队列大小 | | 是否适合动态更新 | 支持动态添加边 | 不易扩展至动态场景 | --- #### 四、注意事项 - 输入验证:确保输入的颜色种类不超过指定范围,可以通过 `std::set` 判断是否存在非法颜色。 - 存储效率:对于大型,建议使用动态分配内存的方式创建邻接表而非固定长度的大数组,以防止堆栈溢出。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值