【问题标题】:Query about number of Connected Components查询连接组件的数量
【发布时间】:2016-05-30 19:28:15
【问题描述】:

我已经编写了代码来查找有向图的连通分量的数量。当我使用下图作为我的邻接矩阵时。它给出的连通分量的数量为 2(第一个 DFS:0->1->2 ,第二个 DFS:3)。

但是当我使用下面的图表作为我的邻接矩阵时

它给出了连接组件的数量为 1(DFS: 0->2->3->1)。所以我想问的是计算连接组件的数量将取决于我们如何在邻接矩阵中表示节点如果我们使用 DFS 来查找 Connected Components 的数量?

代码:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

struct Graph
{
    int V;
    int E;
    int **Adj;
};


void AdjacencyMatrixOfGraph(struct Graph *G)
{
    int u,v,i,j,w;
    scanf("%d %d",&G->E,&G->V);
    G->Adj = (int**)malloc(G->V*sizeof(int *));
    for(i=0;i<G->V;i++)
    {
        G->Adj[i] = (int*)malloc(G->V*sizeof(int));
    }
    for(i=0;i<G->V;i++)
    {
        for(j=0;j<G->V;j++)
        {
            G->Adj[i][j] = 0;
        }

    }
    for(i=0;i<G->E;i++)
    {
        scanf("%d %d",&u,&v);
        G->Adj[u][v] = 1;
        //G->Adj[v][u] = 1;
    }
}
int Visited[1000];
void DFS(struct Graph *G,int u,int Visited[])
{
    Visited[u]=1;
    int v,w,i;
    for(v=0;v<G->V;v++)
    {
        if(G->Adj[u][v] !=0 && Visited[v] == 0)
        {
            //printf("U is %d and V is %d\n",u,v);
            Visited[v] = 1;
            DFS(G,v,Visited);
        }
    }

}

void DFSTraversal(struct Graph *G)
{
    //int Visited[G->V];
    int i;
    int counter = 0;
    for(i=0;i<G->V;i++)
    {
        Visited[i] = 0;
    }
    for(i=0;i<G->V;i++)
    {
        if(!Visited[i])
        {
            DFS(G,i,Visited);
            counter++;
        }
    }
    printf("The Number of Connected Components is %d\n",counter);
}
int main()
{

    struct Graph *graph = (struct Graph *)malloc(sizeof(struct Graph));
    AdjacencyMatrixOfGraph(graph);
    DFSTraversal(graph);
    return 0;

}

【问题讨论】:

    标签: c graph-theory depth-first-search connected-components


    【解决方案1】:

    您的图中没有重要的强连通分量 (SCC)。 (没有从任何顶点到自身的路径。)所以答案“一”和“二”都是错误的;正确答案是四。

    您的算法找不到 SCC。该算法可以在无向图中找到连通分量,但您的邻接表需要修改以使图无向,因为您需要从任一端找到边。

    【讨论】:

    • 我的错误。我写的是强连接组件而不是连接组件。是的,该算法适用于有向图中的连通分量的数量,而不是强连通分量。但是四个?
    • 我不确定说有向图的“连通分量”有多大意义。你会如何定义它?不管它意味着什么,您的算法不会计算它您的算法将计算无向图的连通分量,这是一个定义明确的概念。
    • 感谢您的解释。
    猜你喜欢
    • 2021-06-17
    • 2016-02-12
    • 2012-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多