查询连通分量数

Query about number of Connected Components

我已经编写了代码来查找定向的连通分量数 Graph.When 我使用下图作为我的邻接关系 Matrix.It 给出的连通分量数为 2(第一个 DFS:0 ->1->2,第二个 DFS:3)。

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

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

代码:

#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;

}

您的图中没有非平凡的强连通分量 (SCC)。 (没有从任何顶点到它自己的路径。)所以答案 "one" 和 "two" 都是错误的;正确答案是四。

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